Skip to content

Provide an example of using Newtype and Maybe Newtype #75

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions examples/Newtypes.purs
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
module Example.Newtypes where

import Prelude
import Control.Monad.Except (runExcept)
import Data.Maybe (Maybe)
import Data.Traversable (traverse)
import Effect (Effect)
import Effect.Console (logShow)
import Example.Util.Value (foreignValue)
import Foreign (F, Foreign, readNullOrUndefined, readString)
import Foreign.Index ((!))

newtype Email
= Email String

derive newtype instance showEmail :: Show Email

type SomeObject
= { foo :: String
, bar :: Maybe String
, baz :: Email
, duh :: Maybe Email
}

readObject :: Foreign -> F SomeObject
readObject value = do
foo <- value ! "foo" >>= readString
bar <- value ! "bar" >>= readNullOrUndefined >>= traverse readString
baz <- value ! "baz" >>= readString <#> Email
duh <- value ! "duh" >>= readNullOrUndefined >>= traverse readString <#> map Email
pure { foo, bar, baz, duh }

main :: Effect Unit
main = do
logShow $ runExcept
$ readObject
=<< foreignValue """{ "foo": "a@b.org", "bar": null, "baz": "c@d.net" }"""