Advertisement
STANAANDREY

functs either

Feb 17th, 2025
171
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.  
  2. type Either<E, A> = Left<E> | Right<A>;
  3. interface Left<E> {
  4.     _tag: 'Left',
  5.     value: E
  6. }
  7. interface Right<A> {
  8.     _tag: 'Right',
  9.     value: A
  10. }
  11.  
  12. const left = <E, A=never>(e: E): Either<E, A> => ({
  13.     _tag: 'Left',
  14.     value: e
  15. })
  16.  
  17. const right = <A, E=never>(a: A): Either<E, A> => ({
  18.     _tag: 'Right',
  19.     value: a
  20. })
  21.  
  22. function div2ifeven(num: number): Either<string, number> {
  23.     if (num === 0) {
  24.         return left('/0')
  25.     }
  26.     if (num & 1) {
  27.         return left('odd nr')
  28.     }
  29.     return right(2 / num)
  30. }
  31.  
  32. console.log(div2ifeven(2))
  33. console.log(div2ifeven(0))
  34. console.log(div2ifeven(1))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement