Skip to content

Instantly share code, notes, and snippets.

@masaeedu
Created March 17, 2018 01:58
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 masaeedu/c1406c457bce2b6863aee3407aa10ff0 to your computer and use it in GitHub Desktop.
Save masaeedu/c1406c457bce2b6863aee3407aa10ff0 to your computer and use it in GitHub Desktop.
State monad in JS
// Functor
export const map = f => s => x0 => {
const [v, x1] = s(x0);
return [f(v), x1];
};
// Applicative
export const pure = a => x => [a, x];
export const ap = stf => stv => x0 => {
const [f, x1] = stf(x0);
const [v, x2] = stv(x1);
return [f(v), x2];
};
// Monad
export const chain = f => s => x0 => {
const [v, x1] = s(x0);
return f(v)(x1);
};
import test from "ava";
import * as State from "../state";
test("monad", t => {
// Flip flop between incrementing and decrementing
const transition = State.chain(v => x => [v + x, x * -1]);
const start = State.pure(0)
t.snapshot(1 |> (start |> transition));
t.snapshot(1 |> (start |> transition |> transition));
});

Generated by AVA.

monad

Snapshot 1

[
  1,
  -1,
]

Snapshot 2

[
  0,
  1,
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment