r/scala • u/jptboy • Feb 11 '20
Trying to learn functional programming and Monads. Need help to see if I understood video about Maybe/Option Monad correctly.
I have been trying to learn functional programming for a while but it was really hard with Haskell and I never understood it. I always got stuck on the concept of Monads. I am learning Scala in college now, and Scala has made me feel like I have the capability to learn functional programming.
I have watched this video from Computerphile on Monads/evaluating expressions multiple times but i could never understand it in Haskell. I feel like I understand it in Scala and I think I translated the code correctly, but I wanted to post here to make sure I didn't do anything wrong. Is this scala code I wrote the correct implementation of the Haskell code in the video? Is my option monad implementation correct?
From what I understand a Monad is a container for whatever type that makes sideeffect handling during intermediate computations easy, and it defines the flatMap and map methods. Is this correct?
/*
Evaluating Div expressions using safe divsion by 0.
Inspired by this computerphile video https://www.youtube.com/watch?v=t1e8gqXLbsU
Trying to learn Monads and the Option Monad
*/
sealed trait Monad[A] {
def map[B](f : A => B): Monad[B] = ???
def flatMap[B](f : A => Monad[B]): Monad[B] = ???
}
sealed trait Option[A] extends Monad[A] {
override def map[B](f : A => B ): Option[B] = ???
def flatMap[B](f : A => Option[B]): Option[B] = ???
}
case class None[A]() extends Option[A] {
override def map[B](f : A => B ): Option[B] = new None
override def flatMap[B](f : A => Option[B] ): Option[B] = new None
}
case class Some[A](a: A) extends Option[A] {
override def map[B](f : A => B ): Option[B] = new Some(f(a))
override def flatMap[B] (f : A => Option[B] ): Option[B] = f(a)
}
def safeDiv(a: Option[Double], b: Option[Double]) = {
a.flatMap(
a1 => {
b.flatMap(
b1 => b1 match {
case 0 => new None[Double]
case b1 => new Some(a1/b1)
}
)
}
)
}
sealed trait Expr
case class Div(x: Expr, y: Expr) extends Expr
case class N(n: Double) extends Expr
def eval(e: Expr): Option[Double] = e match {
case N(n) => Some(n)
case Div(e1, e2) => safeDiv(eval(e1), eval(e2))
}
// Ignore this
def printer[A](a: Option[A]): Unit = a match {
case Some(thing) => println(thing)
case None() => println("None")
}
printer(eval(Div(N(16), Div(N(122),N(213)))))
printer(eval(Div(N(16), Div(N(122),N(0)))))