1

我试图更好地理解单子。这是 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

如果这是正确的 - 还有一个最终功能,我对如何概括感到困惑。

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

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

  new Maybe f

现在,您如何将其概括为 lift3,lift4.... liftn 来源:http ://modernjavascript.blogspot.co.uk/2013/06/monads-in-plain-javascript.html

跟进问题:

你能给我一个简单的例子,说明如何将 Maybe Monad 与另一个 Monad 结合起来,为了简单起见,让我们用一个.then方法让它保持 Promise

因为 Monad 的真正用处正在改变它们。

4

1 回答 1

1

Maybe这是在 LiveScript中实现 monad 的一种方式:

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

构造函数接受一个{x}可选参数。Maybe在 Haskell 中是通过对其值构造函数进行模式匹配来实现的。这个有趣的参数是一个 hack,因为 JavaScript (LiveScript) 不支持 SumTypes。

现在我们可以将Justand定义Nothing为:

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

# Nothing :: Maybe x
Nothing = new Maybe null

为了测试我们的 Maybe,让我们定义一个safeSqrt函数:

# 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

此代码将打印Nothing.

liftM2是对任何 monad 进行操作的函数。它需要知道底层 monad 的类型,因为它使用pure(在我们的实现中是一个静态函数):

# 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)

以下是我们如何使用它:

# 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

JSBin 中的代码

于 2016-06-22T14:25:53.930 回答