Skip to content

Instantly share code, notes, and snippets.

@hdgarrood
Created May 20, 2020 15:41
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hdgarrood/d982b0e5441730482d632e7ef172ea55 to your computer and use it in GitHub Desktop.
Save hdgarrood/d982b0e5441730482d632e7ef172ea55 to your computer and use it in GitHub Desktop.
Required and optional fields example
module Main where
import Prelude
import Effect (Effect)
import Data.Foldable (fold)
import TryPureScript (h1, h2, p, text, list, indent, link, render, code)
import Prim.Row (class Union, class Nub)
import Type.Row (type (+))
import Record as Record
type OptionalFields r = ( x :: Int, y :: Int | r )
type RequiredFields = (a :: Int)
type AllFields = OptionalFields + RequiredFields
goo ::
forall given allFields.
-- We need a separate allFields type variable because it's not the same as the AllFields synonym,
-- in that it will have duplicate labels. That's what the Nub constraint is for.
Union given (OptionalFields ()) allFields =>
Nub allFields AllFields =>
Record given ->
String
goo r =
let
defaults :: Record (OptionalFields ())
defaults = { x: 2, y: 3 }
m :: Record AllFields
m = Record.merge r defaults
in
show m
main :: Effect Unit
main =
render $ fold
[ h1 (text "Try PureScript!")
, p (text (goo { a: 3 }))
, p (text (goo { a: 1, x: 10 }))
, p (text (goo { a: 1, y: 10 }))
, p (text (goo { a: 1, x: 9, y: 10 }))
-- doesn't compile
-- , p (text (goo { x: 2 }))
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment