Skip to content

Instantly share code, notes, and snippets.

@telekosmos
Created September 20, 2022 12:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save telekosmos/03833734616d70768b3a68adb4d9d45a to your computer and use it in GitHub Desktop.
Save telekosmos/03833734616d70768b3a68adb4d9d45a to your computer and use it in GitHub Desktop.
Tree and map
import * as O from 'fp-ts/Option'
import { pipe } from 'fp-ts/function'
// interface Tree<A> {
type Tree<A> = {
readonly left: O.Option<Tree<A>>
readonly data: A
readonly right: O.Option<Tree<A>>
}
const subt: Tree<number> = { left: O.none, data: 7, right: O.none }
const t: Tree<number> = {
left: O.some(subt),
data: 5,
right: O.none
}
const treeMap = <A, B>(f: (a: A) => B) => (ts: Tree<A>): Tree<B> => {
return {
data: f(ts.data),
left: O.map(treeMap(f))(ts.left),
right: O.map(treeMap(f))(ts.right),
}
}
const mapResult = treeMap<number, number>(x => x * 3)(t)
mapResult
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment