HasField型クラス
定義
code:hs
class HasField x r a | x r -> a where
getField :: r -> a
型引数の意味
xは、fieldの名前
rは、Record
aは、Recordにおけるfieldの型
例
code:hs
data User = User
{ name :: Text
, age :: Int
}
code:hs
instance HasField "name" User Text where
getField :: User -> Text
getField = name
instance HasField "age" User Int where
getField :: User -> Int
getField = age
これでアクセスできる
code:hs
{-# LANGUAGE TypeApplications #-} {-# LANGUAGE DataKinds #-} import GHC.Records (HasField (getField))
getField @"name" (User "hoge" 42) -- "hoge"
getField @"age" (User "hoge" 42) -- 42
参考