Last active
August 16, 2019 20:07
-
-
Save glebec/67d9b90b7fba2b72f105670495410097 to your computer and use it in GitHub Desktop.
Scott Encoding
This file contains hidden or 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
/** | |
* -- Haskell `Maybe` type: | |
* data Maybe a = Nothing | Just a | |
*/ | |
// JS Scott-Encoding-inspired `Maybe` definition | |
// (NB, true Scott encoding uses closures rather than a record – see gist comment) | |
const Maybe = { | |
Nothing: whatToDoInEachCase => { | |
return whatToDoInEachCase.Nothing; | |
}, | |
Just: a => whatToDoInEachCase => { | |
return whatToDoInEachCase.Just(a); | |
} | |
}; | |
// some sample values to play with | |
const example1 = Maybe.Nothing; | |
const example2 = Maybe.Just(5); | |
const example3 = Maybe.Nothing; | |
const example4 = Maybe.Just("hi"); | |
const example5 = Maybe.Just(true); | |
[example1, example2, example3, example4, example5].forEach(example => { | |
// example of how to "pattern match" on these vals | |
const result = example({ | |
Nothing: "there was nothing here", | |
Just: a => "there was something here: " + a | |
}); | |
console.log(result); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
PPS conversely, the JS sum type encoding can be made slightly more idiomatic as follows: