Skip to content

Instantly share code, notes, and snippets.

@zerobias
Created March 27, 2018 14:19
Show Gist options
  • Save zerobias/d986912bd6c9746ef9c0bfa774ea2cfc to your computer and use it in GitHub Desktop.
Save zerobias/d986912bd6c9746ef9c0bfa774ea2cfc to your computer and use it in GitHub Desktop.
Applicative wrapper

Make native Set<T> applicative via wrapper

//@flow
import {interpret} from './wrap'
const foo = () => interpret(new Set([0, 1, 2]))
.map(x => x + 1)
.ap( interpret(new Set([x => x * 10])) )
//@flow
export const interpret = <A>(set: Set<A>) => ({
of(value: A) {
return interpret(new Set([value]))
},
empty(){ return interpret(new Set()) },
map<B>(fn: A => B) {
return interpret(
new Set(map(fn, set))
)
},
ap<B>(fnSet: Set<(_: A) => B>) {
return interpret(
new Set([...fnSet].reduce(
(acc, fn) => [...acc, ...map(fn, set)],
[]
))
)
}
})
function map<A, B>(fn: A => B, set: Set<A>): B[] {
return [...set].map(fn)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment