例
type alias Guid= String
type alias Player =
{ name: String
, active: Bool
, id: Guid
}
player : Decoder Player
player =
succeed Player
|: ("name" := string)
|: ("active" := bool)
|: ("id" := string)
例
{-# LANGUAGE DeriveGeneric#-}
type Guid = String
data Player =
{ name : String
, active : Bool
, id : Guid
} deriving (Generics, Show)
instance FromJSON Player
instance ToJSON Player
例
こういう型から
data Comment =Comment
{ postId :: Int
, text :: Text
, mainCategories :: (String, String)
, published :: Bool
, created :: UTCTime
} deriving (Generic, ElmType)
17.
例
type alias Comment=
{ postId : Int
, text : String
, mainCategories : (String, String)
, published : Bool
, created : Date
}
decodeComment : Decoder Comment
decodeComment =
decode Comment
|> required "postId" int
|> required "text" string
|> required "mainCategories"
(map2 (,) (index 0 string) (index 1 string))
|> required "published" bool
|> required "created" decodeDate
例
extensible というヤバいパッケージを使う
type Player= Record
'[ "name" >: String
, "active" >: Bool
, "id" >: Guide
]
player :: Player
player =
#name @= "hige" <: #active @= True <: #id @= "123" <: emptyRecord
player ^. #name
参照には lens というヤバいパッケージを使う
23.
拡張可能レコードの JSON は??
これです
instanceForall (KeyValue KnownSymbol FromJSON) xs =>
FromJSON (Record xs) where
parseJSON = withObject "Object" $
v -> hgenerateFor
(Proxy :: Proxy (KeyValue KnownSymbol FromJSON)) $
m -> let k = symbolVal (proxyAssocKey m) in
case HM.lookup (fromString k) v of
Just a -> Field . return <$> parseJSON a
Nothing -> fail $ "Missing key: " `mappend` k
(雑に言えば)
拡張可能レコードという一つの型として扱う
24.
まとめ
Elm で JSONはつらい?
つ elm-format with Haskell
Elm のレコード型を Haskell で書けない?
つ 拡張可能レコード
実際に ElmとHaskellでサンプル書いた記事 がある
ので詳しくはコレを見て(?)
Haskell 最高じゃん