SHARE
TWEET

Untitled

a guest May 19th, 2019 64 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // Functor manda objetos de una categoria a otra
  2. // Manda identidad a identidad y composicion a composicion
  3.  
  4. Sealed Trait Option[+A] {
  5.   def map[B](f : A => B) : Option[B] = this.flatMap(a : A => Option.lift(f(a)))
  6.   def flatMap[B](f : A => Option[B]) : Option[B]
  7. }
  8.  
  9. case object None extends Option[Nothing] {
  10.   override def flatMap[A] (f : A => Option[B] ) : Option[B] = this
  11.   override def map[B] (f : A => B) : Option[B] = this
  12.  
  13. }
  14. case class Some[+A] (d : A) extends Option[A] {
  15.   override def flatMap[A](f : A => Option[B]) : Option[B] = f(d)
  16.   override def map[B] (f : A => B) : Option[B] = Some(f(d))
  17. }
  18.  
  19. // Chequear que flatMap es asociativo
  20.  
  21. object Option {
  22.   def lift[A](d : A) : Option[A] = Some(d)
  23.  
  24.   def product[A,B] (fa : Option[A], fb : Option[B]) : Option[A,B] = {
  25.     fa.flatMap(a => fb.flatMap(b => Option.lift(a,b)))
  26.   }
  27.  
  28.   def map2[A,B,C] (a : Option[A])(b : Option[B])(f : (A,B) => C) : Option[C] = {
  29.     product[a,b].map(f)
  30.   }
  31. }
  32.  
  33. // Aplicativo (apply)
  34. // Functor que tiene un pure y un map 2
  35. // Todo functor con estructura de monada tiene estructura de aplicativo
  36. // Pero no necesariamente un aplicativo tiene estructura de monada
  37.  
  38. // Tener map2 y apply es equivalente
  39. // lift + map2 = map => apply
  40. // lift + apply = map => map2
  41.  
  42. def map[B] (f : A => B) : Option[B] = {
  43.   Option.apply[A,B](Option.lift(f))(this)
  44. }
  45.  
  46. // Apply en terminos de map2
  47.  
  48. def apply[A,B](f : Option[A=>B])(fa : Option[A]) = {
  49.   map2((x,y)=>x(y))(f,fa)
  50. }
  51.  
  52. // Map2 en terminos de Apply
  53. def map2[A,B,C](fa : Option[A], fb : Option[B])(f : (A,B) => C) : Option[C] ={
  54.   Option.apply(Option.pure(f))(Option.product(fa,fb))
  55. }
  56.  
  57. // Pero product usa flatMap, hay que re-escribirlo SIN flatMap
  58.  
  59. def product[A,B](fa Option[A], fb : Option[B]) : Option[A,B] = {
  60.   Option.apply(fa.map(a => (b : B) => (a,b)))(fb)
  61. }
  62.  
  63. // Probar que flatMap es asociativo
  64. // Probar que map respeta la composicion
  65. // Leer sobre trampolines y free monads
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top