Advertisement
Andrea_00

Scala Code of Andrea Munarin 10/03/00 for Bending Spoons

Feb 29th, 2024 (edited)
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 1.16 KB | Source Code | 0 0
  1. /**
  2.   * Redefine the Monad type class for the Maybe type
  3.   */
  4. enum MyMaybe[+A]:
  5.     case OK(x: A)
  6.     case KO
  7.  
  8. /**
  9.   * Define the Monad type class. For the Monad type class, define the unit, flatmap and map methods.
  10.   */
  11. trait Monad[F[_]]:
  12.     def unit[A](z: A): F[A]
  13.     extension[A](o: F[A])
  14.         def flatmap[B](f: A=>F[B]): F[B]
  15.         def map[B](f: A=>B): F[B]
  16.  
  17. import MyMaybe.*
  18.  
  19. /**
  20.   * Define the Monad type class for the Maybe type implementing the unit, flatmap and map methods.
  21.   */
  22. given Monad[MyMaybe] with
  23.     def unit[A](z:A):MyMaybe[A] = OK(z)
  24.     extension [A](o: MyMaybe[A])
  25.         def flatmap[B](f: A=>MyMaybe[B]): MyMaybe[B] =
  26.             o match
  27.                 case KO=>KO
  28.                 case OK(x)=>f(x)
  29.         def map[B](f: A=>B): MyMaybe[B] =
  30.             o match
  31.                 case KO=>KO
  32.                 case OK(x)=>unit((f(x)))
  33.  
  34. /**
  35.   * Define the perdue method that takes a T[Int] and returns a T[Int] with the value doubled.
  36.   * T is a Monad or a subtype of Monad
  37.   * @param o the T[Int] to double
  38.   * @return the T[Int] with the value doubled
  39.   */
  40. def perdue[T[_]:Monad](o:T[Int]):T[Int]=
  41.     o.map(x=>x*2)
  42.  
  43.  
  44.  
Tags: Scala
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement