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。
现在我们可以将Just
and定义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 中的代码