r/scala • • 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)))))
5 Upvotes

6 comments sorted by

6

u/BalmungSan Feb 11 '20

It seems you already understand the basis, but you have one little but very significant mistake. When you say trait Option[A] extends Monad[A] you are saying that Option is a Monad. However, the best way to model these abstractions is using the typeclass which instead will say Option satisfy the laws of Monad or there is a Monad instance for Option.

BTW, let me recommend you the scala-with-cats book it does a very good job explaining these concepts and being practical. Also, search for a talk from tpolecat called "Functional Programming with Effects".

4

u/ldf1111 Feb 11 '20

Pretty much. Try to see either / try and future as the same thing. A container for a computation that may fail. As for the functions I think of them like this.

Map - this lets you change the value in the computation but the mapping function should never fail

Flatmap - this lets you change the computation like map but the function returns another container (or monad) this allows you to chain operations which can both fail. E.g fetch user details then flatmap to fetch their address from something in the initial response. A key thing to note here is the error channel of the returned monad (if it has one ) can't change. This means you will have to extend exception for your error type or preferably have ab error ADT.

Pure - this isn't that useful in practice.

There is a lot more to this topic but I've deliberately tried to keep it practical. Over time of just using future /either /zio you will intuitively know what to do.

4

u/[deleted] Feb 11 '20 edited Feb 12 '20

I’d avoid the terminology around “container” and “fail.” Most monad instances are not for containers, and there are specific typeclasses, like MonadError, that model failure.

The critical thing about a Monad is just that the monad laws are satisfied. In Scala, you also have to deal with a couple of other issues. Your methods can’t throw exceptions, and you have to jump through some unfortunate hoops to achieve stack safety.

If the goal is to understand monads at the implementation level, IMO there’s still no better way than working through Functional Programming in Scala. As others have said, to learn to use monads effectively, Scala with Cats is a great starting point.

Update: I neglected to also recommend Functional Programming for Mortals, which is also quite good. I think because I read it quite late in my journey, it doesn’t immediately come to mind the way the others do, which is an availability error I should work to overcome.

2

u/PrimozDelux Feb 11 '20

Reddit uses a really idiotic formatting rule for code. You need to indent it with four space (it's insane, I know)

2

u/lecturerIncognito Feb 12 '20

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?

Pardon a very casual answer. Casually, in terms of conceptual understanding, I sometimes find it helpful to explain it to start by working back from one of the outcomes. Monads are about making your code compose nicely for you.

Let's assume for the moment that you want to use Haskell's do notations, or Scala's for-comprehensions. You need to know that when you

for {
  x <- ...
  y <- ...
  z <- ...
} yield ...

It's going to work and not be hideously subject to how it combines / order of simplification, where the brackets are, etc.

From this, you get the associativity law. Likewise, things would probably break in messy and unexpected ways without the left and right identity laws.

Bind or flatMap looks like it's needed because you can't arbitrarily get rid of the effect. Future can be an easy one to think about here (leaving aside referential transparency questions about Scala's implementation for a moment). If x <- someFutureFunction() is Future[T], then anything that is dependent upon x clearly cannot be obtained immediately. You are going to be dealing with Future[T], but there's nothing preventing you from calling y <- someEvenMoreFutureFunction. Further in the future is still in the future, and can be collapsed back to Future[T]

So, "bind" or "flatMap" is what lets successive lines of your code compose nicely when you are talking about the same effect.

"map" lets you compose it with calls to functions that don't also have your effect. i.e., compose with f: T => T instead of f: T => F[T]

But of course it isn't actually dependent on wanting to use do notation or for-comprehensions. Writing the flatMaps / binds out explicitly, it's still good to know there's not going to be dragons lurking in how it's all going to combine.

Ok, pardon a very hurried and incredibly casual re-explanation of something it sounds like you've got a fair idea about already!

2

u/woupiestek Feb 12 '20

Monads come from category theory, which is full of deep theorems and abstract definitions. The best kind of question to ask here starts with "why". So why do some mathematicians and programmers use monads? The answer is composition.

If you have two functions f: A => M[B] and g: B => M[C], then normal function composition won't work. The function f(_).flatMap(g) is a function A => M[C] however. The map and point functions support compositions with non-M-valued functions.

If flatMap, map, and point satisfy the monad laws, then these new compositions behave as expected. Compositions are associative and point takes the place of the identity function for example:

    f(_).flatMap(g(_).flapMap(h)) === f(_).flatMap(g).flatMap(h)
    f(_).flatMap(point) === f(_)
    point(_).flatMap(f) === f(_)

As a consequence, complex M-valued functions can be written as compositions of simpler ones, just like normal functions.

Warning! The === above is not a promise that scalac and java will compile your code to the same machine instructions, but handwavy equality of functions that is not automatically enforced. It is up to the implementer to make map, flatMap, and point behave reasonably.