Skip to content

Instantly share code, notes, and snippets.

@and-pete
Last active December 22, 2021 06:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save and-pete/a129c66339baabe7d083357e09a3ffdc to your computer and use it in GitHub Desktop.
Save and-pete/a129c66339baabe7d083357e09a3ffdc to your computer and use it in GitHub Desktop.
TryPureScript.org example
module Main where
import Prelude
import Data.Codec.Argonaut as CA
import Data.Codec.Argonaut (JsonDecodeError)
import Data.Codec.Argonaut.Record as CAR
import Data.Codec.Argonaut.Common as CAC
import Data.Argonaut.Parser as AP
import Data.Argonaut.Core as AC
import Data.Argonaut.Core (Json)
import Data.Either
import Data.Maybe
import Data.Time.Duration
import Effect
import Effect.Class
import Effect.Aff
import Effect.Aff as Aff
import Effect.Aff.Class
import Effect.Class.Console (log, logShow)
import TryPureScript (render, withConsole)
transform :: Json -> Either JsonDecodeError String
transform = CA.decode CA.string
type Person = { name :: String, age :: Number }
main :: Effect Unit
main = render =<< withConsole do
------------
-- | Values
------------
let
person = { person: { name: "Alice McBob", age: 42.69 } }
personCodec =
CAR.object "PERSON"
{ person: CAR.object "PERSON inner" { name: CA.string, age: CA.number}
}
encodedPerson = AC.stringify (CA.encode personCodec person) :: String
---------
-- | I/O
---------
heading "PERSON"
logShow person
heading "PERSON encoded as Json"
logShow encodedPerson
heading "PARSING & RE-DECODING PERSON"
case AP.jsonParser encodedPerson of
Left error1 -> log error1
Right json ->
case CA.decode personCodec json of
Left error2 -> log $ CA.printJsonDecodeError error2
Right person' -> logShow person'
----------------------------------------
-- | Stuff
----------------------------------------
heading :: forall m. MonadEffect m => String -> m Unit
heading txt = log $ "\n=== " <> txt <> "===\n"
withLabel :: forall m. MonadEffect m => String -> String -> m Unit
withLabel label txt = log $ "[ " <> label <> " ] " <> txt
delay :: String -> Number -> Aff Unit
delay label secs = do
withLabel label $ "Delaying " <> show secs <> " seconds"
Aff.delay (convertDuration $ Seconds secs)
withLabel label $ "Delay of " <> show secs <> " seconds complete!"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment