haskell - What exactly makes Option a monad in Scala? -
i know monads , how use them. don't understand what makes, let's say, option
monad?
in haskell monad maybe
monad because it's instantiated monad
class (which has @ least 2 necessary functions return
, bind
makes class monad
, indeed, monad).
but in scala we've got this:
sealed abstract class option[+a] extends product serializable { ... } trait product extends equals { ... }
nothing related monad.
if create own class in scala, monad default? why not?
monad
concept, abstract interface if will, defines way of composing data.
option
supports composition via flatmap
, , that's pretty needed wear "monad badge".
from theoretical point of view, should also:
- support
unit
operation (return
, in haskell terms) create monad out of bare value, in case ofoption
some
constructor - respect monadic laws
but not strictly enforced scala.
monads in scala looser concept in haskell, , approach more practical. thing monads relevant for, language perspective, ability of being used in for-comprehension.
flatmap
basic requirement, , can optionally provide map
, withfilter
, foreach
.
however, there's no such thing strict conformance monad
typeclass, in haskell.
here's example: let's define our own monad.
class mymonad[a](value: a) { def map[b](f: => b) = new mymonad(f(value)) def flatmap[b](f: => mymonad[b]) = f(value) override def tostring = value.tostring }
as see, we're implementing map
, flatmap
(well, , tostring
commodity). congratulations, have monad! let's try out:
scala> { <- new mymonad(2) b <- new mymonad(3) } yield + b // res1: mymonad[int] = 5
nice! not doing filtering, don't need implement withfilter
. since we're yielding value, don't need foreach
either. implement whatever wish support, without strict requirements. if try filter in for-comprehension , haven't implemented withfilter
, you'll compile-time error.
Comments
Post a Comment