1

I am trying to understand monads better. Is this minimal implementation of a Maybe Monad Correct ?

Maybe = (value) ->

    @value = value

Maybe.prototype.ret = -> @value

Maybe.prototype.bind = (fn) ->

    if not (@value is null)

        return fn @value

    @value

Maybe.prototype.lift = (fn) -> (val) -> new Maybe fn val

also if this is correct - there is a final function that I am confused about how to generalize.

Maybe.prototype.lift2 = (fn) -> (M1, M2) ->

  f = M1.bind ((val1) -> M2.bind (val2) -> fn val1, val2)

  new Maybe f

Now how do you generalize this for lift3,lift4.... liftn Source : http://modernjavascript.blogspot.co.uk/2013/06/monads-in-plain-javascript.html

Follow Up Question:

Could you give me a simple example of how to combine the Maybe Monad with another Monad for simplicity sake lets keep it a Promise with a .then method

Since the real usefulness of Monads are transforming them.

sourcevault
  • 313
  • 1
  • 3
  • 10

1 Answers1

1

This is one way of implementing Maybe monad in LiveScript:

class Maybe
  ({x}:hasValue?) ->

    # map :: [Maybe a -> ] (a -> b) -> Maybe b
    @map = (f) ->
      if !hasValue then Nothing else Just (f x)

    # bind :: [Maybe a -> ] (a -> Maybe b) -> Maybe b
    @bind = (f) ->
      if !hasValue then Nothing else f(x)

    # toString :: [Maybe a -> ] String
    # note here it's not necessary for toString() to be a function
    # because Maybe is can only have either one these values: 
    # Nothing or Just x
    @show =
      if !hasValue then 'Nothing' else "Just #{x.toString!}"

  # static method
  @pure = (x) -> Just x

The constructor takes an optinal {x} parameter. Maybe in Haskell is implemented by pattern matching on its value consturctors. This funny parameter is a hack around it, because JavaScript (LiveScript) doesn't support SumTypes.

Now we can define Just and Nothing as:

# Just :: x -> Maybe x
Just = (x) -> new Maybe {x}

# Nothing :: Maybe x
Nothing = new Maybe null

To test our Maybe, let's define a safeSqrt function:

# safeSqrt :: Number -> Maybe Number
safeSqrt = (x) ->
  if x > 0 then Just (Math.sqrt x) else Nothing

# operation :: Maybe Number
operation = do ->
  a = Just 4
    .map (x) -> x * -16
    .bind safeSqrt

console.log operation.show

This code will print Nothing.

liftM2 is a function that operates on any monad. It needs to know the type of the underlying monad, because it uses pure (that in our implementation is a static function):

# liftM2 :: Monad m => (a -> b -> c) -> m a -> m b -> m c
liftM2 = (monadType, f, m1, m2) -->
  x1 <- m1.bind
  x2 <- m2.bind
  monadType.pure (f x1, x2)

Here's how we can use it:

# operation :: Maybe Number
operation = do ->
  a = Just 4
    .map (x) -> x * 16
    .bind safeSqrt
  b = safeSqrt 81

  liftM2 Maybe, (+), a, b

console.log operation.show

Code in JSBin

homam
  • 1,945
  • 1
  • 19
  • 26