Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Redefine the Monad type class for the Maybe type
- */
- enum MyMaybe[+A]:
- case OK(x: A)
- case KO
- /**
- * Define the Monad type class. For the Monad type class, define the unit, flatmap and map methods.
- */
- trait Monad[F[_]]:
- def unit[A](z: A): F[A]
- extension[A](o: F[A])
- def flatmap[B](f: A=>F[B]): F[B]
- def map[B](f: A=>B): F[B]
- import MyMaybe.*
- /**
- * Define the Monad type class for the Maybe type implementing the unit, flatmap and map methods.
- */
- given Monad[MyMaybe] with
- def unit[A](z:A):MyMaybe[A] = OK(z)
- extension [A](o: MyMaybe[A])
- def flatmap[B](f: A=>MyMaybe[B]): MyMaybe[B] =
- o match
- case KO=>KO
- case OK(x)=>f(x)
- def map[B](f: A=>B): MyMaybe[B] =
- o match
- case KO=>KO
- case OK(x)=>unit((f(x)))
- /**
- * Define the perdue method that takes a T[Int] and returns a T[Int] with the value doubled.
- * T is a Monad or a subtype of Monad
- * @param o the T[Int] to double
- * @return the T[Int] with the value doubled
- */
- def perdue[T[_]:Monad](o:T[Int]):T[Int]=
- o.map(x=>x*2)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement