Skip to content

Instantly share code, notes, and snippets.

@glebec
Last active August 16, 2019 20:07
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save glebec/67d9b90b7fba2b72f105670495410097 to your computer and use it in GitHub Desktop.
Save glebec/67d9b90b7fba2b72f105670495410097 to your computer and use it in GitHub Desktop.
Scott Encoding
/**
* -- 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);
});
@glebec
Copy link
Author

glebec commented Mar 14, 2019

PS the true Scott encoding in the lambda calc sense would be:

const Nothing =      whatToDoForNothing => whatToDoForJust => whatToDoForNothing
const Just    = a => whatToDoForNothing => whatToDoForJust => whatToDoForJust(a)

And then you would use it like so:

const example = (Math.random() < 0.5) ? Nothing : Just(5)

const result = example(
    "there was nothing here"
)(
    a => "there was something here: " + a
)

Using an object to have named "pattern matching" is a bit more JS-idiomatic / convenient in most cases however.

@glebec
Copy link
Author

glebec commented Mar 14, 2019

PPS conversely, the JS sum type encoding can be made slightly more idiomatic as follows:

const Maybe = {
    Nothing: {
        match: patterns => patterns.Nothing
    },
    Just: a => {
        match: patterns => patterns.Just(a)
    }
}

const example = (Math.random() < 0.5) ? Maybe.Nothing : Maybe.Just(5)

const result = example.match({
    Nothing: "there was nothing here",
    Just: a => "there was something here: " + a
})

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment