Created
September 20, 2022 12:56
-
-
Save telekosmos/03833734616d70768b3a68adb4d9d45a to your computer and use it in GitHub Desktop.
Tree and map
This file contains 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
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