Created
May 20, 2020 15:41
-
-
Save hdgarrood/d982b0e5441730482d632e7ef172ea55 to your computer and use it in GitHub Desktop.
Required and optional fields example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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