Created
November 1, 2021 01:09
-
-
Save kalda341/721308828b041c6a4d8b0183c243969d to your computer and use it in GitHub Desktop.
This file contains hidden or 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 "./styles.css"; | |
import { function as F, option as O, readonlyArray as A, monoid as Monoid, readonlyNonEmptyArray as NEA } from 'fp-ts'; | |
import { some } from "fp-ts/lib/ReadonlyRecord"; | |
export default function App() { | |
return ( | |
<div className="App"> | |
<h1>Hello CodeSandbox</h1> | |
<h2>Start editing to see some magic happen!</h2> | |
</div> | |
); | |
} | |
type Some<T> = { | |
readonly type: 'some'; | |
readonly some: T; | |
}; | |
type None = { | |
readonly type: 'none'; | |
}; | |
// Sum type { Some, None } | |
type Option<T> = Some<T> | None; | |
const ofSome = <T,>(x: T): Some<T> => { | |
return { | |
type: 'some', | |
some: x | |
}; | |
} | |
const none: None = { | |
type: 'none', | |
}; | |
// map = <F, T, U>(f: (x: T) => U) => (F<T>): F<U>; | |
const mapSome = <T, U>(f: (x: T) => U) => (x: Some<T>): Some<U> => { | |
return ofSome(f(x.some)); | |
} | |
const mapOption = <T, U>(f: (x: T) => U) => (x: Option<T>): Option<U> => { | |
switch (x.type) { | |
case 'some': | |
return mapSome(f)(x); | |
case 'none': | |
return none; | |
} | |
} | |
const flatOption = <T,>(x: Option<Option<T>>): Option<T> => { | |
switch (x.type) { | |
case 'none': | |
return none; | |
case 'some': { | |
return x.some; | |
} | |
} | |
} | |
// chain (flatMap) = <M, T, U>(f: (x: T) => M<U>) => (M<T>): F<U>; | |
// chain = flatten(map) | |
// anything with chain, must also have map | |
// any monad, is a functor | |
const chainOption = <T, U>(f: (x: T) => Option<U>) => (x: Option<T>): Option<U> => { | |
return F.pipe( | |
x, | |
mapOption(f), | |
flatOption | |
) | |
} | |
const invert = (x: number): Option<number> => { | |
if (x === 0) { | |
return none; | |
} else { | |
return ofSome(1 / x); | |
} | |
} | |
const addOne = (x: number): number => x + 1; | |
const result = F.pipe( | |
invert(0), | |
mapOption(addOne), | |
mapOption(addOne), | |
mapOption(addOne), | |
chainOption(invert), | |
chainOption(invert), | |
chainOption(invert) | |
) | |
const a = F.pipe( | |
[1, 2, 3], // [1, 2, 3] | |
A.map((x) => [x, x * x]), // [[1, 1], [2, 4], [3, 9]] | |
A.flatten, // [1, 1, 2, 4, 3, 9] | |
A.map((x) => x + 1), // [2, 2, 3, 5, 4, 10] | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment