Advertisement
STANAANDREY

functs maybe option

Feb 16th, 2025
273
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. type Composer = <A, B, C> (
  2.     f: (x: B) => C,
  3.     g: (x: A) => B,
  4. ) => (x: A) => C
  5. const compose: Composer = (f, g) => x => f(g(x))
  6.  
  7. type Option<A> = Some<A> | None
  8. interface Some<A> {
  9.     _tag: 'Some',
  10.     value: A
  11. }
  12. interface None {
  13.     _tag: 'None'
  14. }
  15.  
  16. const some = <A>(x: A): Option<A> => ({ _tag: 'Some', value: x })
  17. const none: Option<never> = {_tag: 'None'}
  18.  
  19. const isNone = <A>(x: Option<A>): x is None => x._tag === 'None'
  20.  
  21. type Inc = (x: number) => number
  22. const inc: Inc = x => x + 1
  23.  
  24. type Div2 = (x: number) => Option<number>
  25. const div2: Div2 = x => x === 0 ? none : some(2/x)
  26.  
  27. const composed = compose(
  28.     (x: Option<number>) => isNone(x) ? none : some(inc(x.value)),
  29.     div2
  30. )
  31.  
  32. console.log(composed(4))
  33. console.log(composed(0))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement