2014-01-24 116 views
0

如果我们在monadPlusSDif,Maybe处选择它们作为MonadPlus的数据类型,那么这两个功能是否等效?Haskell Monad等效

tdif :: Int -> Int -> Maybe Int 
tdif x y 
    | y == 0 = Nothing 
    | otherwise = Just (div x y) 

monadPlusSDif :: MonadPlus m => Int -> Int -> m Int 
monadPlusSDif x y = guard (y /= 0) >> return (div x y) 
+5

将来,请花时间将代码输入到Stackoverflow编辑器中,代码图片不会考虑其他想要帮助的人。 – bheklilr

回答

5

这些功能将具有同等的行为,如果m ~ Maybe,但他们的编译后的字节码表示可能会有所不同。你也可以用一般MonadPlus单子实际警卫实现它作为

monadPlusSDif :: MonadPlus m => Int -> Int -> m Int 
monadPlusSDif x y 
    | y == 0 = mzero 
    | otherwise = return $ x `div` y 

然后,你可以使用它作为

bigEquation :: Int -> Int -> Maybe Int 
bigEquation x y = do 
    z1 <- monadPlusSDif x y 
    z2 <- monadPlusSDif (x + y) (x - y) 
    z3 <- monadPlusSDif y x 
    return $ z1 + z2 * z3 

,编译器将能够弄清楚,在这种情况下,它应该使用Maybem

9

嗯,MaybeMonadPlus实例

instance MonadPlus Maybe where 
    mempty = Nothing 

guard作为

guard b = if b then return() else mempty 
--  = if b then Just () else Nothing 

知道这一点实现,你可以用等式推理来推断,当mMaybe,你可代替原代码

monadPlusSDif x y = guard (y /= 0) >> return (div x y) 

monadPlusSDif x y = (if y /= 0 
    then Just() 
    else Nothing) >> Just (div x y) 

monadPlusSDif x y 
    | y /= 0 = Just() >>= \_ -> Just (div x y) 
    | otherwise = Nothing >>= \_ -> Just (div x y) 

monadPlusSDif x y 
    | y /= 0 = Just (div x y) 
    | otherwise = Nothing 

monadPlusSDif x y 
    | y == 0 = Nothing 
    | otherwise = Just (div x y) 

,所以你看到的功能是相同的。