Skip to content

Instantly share code, notes, and snippets.

@matsubara0507
Created April 29, 2019 05:33
Show Gist options
  • Save matsubara0507/0d0fe2fa59171547ee438dacb0cf6d9c to your computer and use it in GitHub Desktop.
Save matsubara0507/0d0fe2fa59171547ee438dacb0cf6d9c to your computer and use it in GitHub Desktop.
JSON with default value using Nullable
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE OverloadedLabels #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE TypeOperators #-}
module DefaultJson where
import Data.Aeson
import Data.Extensible
import Data.Maybe (fromMaybe)
type Foo = Record FooFields
type FooFields =
'[ "a" >: Int
, "b" >: Int
]
type Foo' = Nullable (Field Identity) :* FooFields
defaultFoo :: Foo
defaultFoo
= #a @= 10
<: #b @= 50
<: nil
fromNullable :: RecordOf h xs -> Nullable (Field h) :* xs -> RecordOf h xs
fromNullable def =
hmapWithIndex $ \m x -> fromMaybe (hlookup m def) (getNullable x)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment