Created
September 11, 2017 11:19
-
-
Save ncaq/d6bbda8dca9d7d6462509ac10a11eb1a to your computer and use it in GitHub Desktop.
OverloadedRecordFieldsのサンプル
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{-# LANGUAGE DataKinds #-} | |
{-# LANGUAGE DuplicateRecordFields #-} | |
{-# LANGUAGE FlexibleInstances #-} | |
{-# LANGUAGE MultiParamTypeClasses #-} | |
{-# LANGUAGE NamedFieldPuns #-} | |
{-# LANGUAGE OverloadedLabels #-} | |
{-# LANGUAGE TypeFamilies #-} | |
module OverloadedRecordFieldsExample where | |
import GHC.OverloadedLabels | |
data Point2 = | |
Point2 | |
{ x :: Double | |
, y :: Double | |
} | |
deriving (Eq, Ord, Show, Read) | |
instance IsLabel "x" (Point2 -> Double) where | |
fromLabel _ Point2 { x } = x | |
instance IsLabel "y" (Point2 -> Double) where | |
fromLabel _ Point2 { y } = y | |
data Point3 = | |
Point3 | |
{ x :: Double | |
, y :: Double | |
, z :: Double | |
} | |
deriving (Eq, Ord, Show, Read) | |
instance IsLabel "x" (Point3 -> Double) where | |
fromLabel _ Point3 { x } = x | |
instance IsLabel "y" (Point3 -> Double) where | |
fromLabel _ Point3 { y } = y | |
instance IsLabel "z" (Point3 -> Double) where | |
fromLabel _ Point3 { z } = z | |
class Normalize a where | |
normalize :: a -> a | |
instance Normalize Point2 where | |
normalize Point2{ x, y } = let base = sqrt $ x ^ (2 :: Int) + y ^ (2 :: Int) | |
in Point2 { x = x / base, y = y / base } | |
instance Normalize Point3 where | |
normalize Point3{ x, y, z } = let base = sqrt $ x ^ (2 :: Int) + y ^ (2 :: Int) + z ^ (2 :: Int) | |
in Point3 { x = x / base, y = y / base, z = z / base } | |
point2X :: Point2 -> Double | |
point2X = #x | |
point2Y :: Point2 -> Double | |
point2Y = #y |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment