Maybeこれは、LiveScript でモナドを実装する 1 つの方法です。
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}パラメーターを取ります。MaybeHaskell では、値コンストラクターのパターン マッチングによって実装されます。JavaScript (LiveScript) は SumTypes をサポートしていないため、この面白いパラメータはハックです。
Justこれで、 andNothingを次のように定義できます。
# Just :: x -> Maybe x
Just = (x) -> new Maybe {x}
# Nothing :: Maybe x
Nothing = new Maybe null
safeSqrtMaybe をテストするために、関数を定義しましょう。
# 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任意のモナドで動作する関数です。以下を使用するため、基礎となるモナドの型を知る必要があります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 のコード