我是哈斯克尔的新人。这是我的计划:
maybe_divide :: Maybe Integer -> Maybe Integer -> Maybe Integer
maybe_divide a b = case (a, b) of
(Just a, Just b)
| (Just a, Just b)
| (Nothing, _) -> Nothing
| (_, Just 0) -> Nothing
| (_, Nothing) -> Nothing
| (Just a,Just b) -> Just (a `div` b)
编译器显示:表达式上下文中的模式语法:_。 当我只使用没有防护装置的情况时它起作用。为什么它不能在警卫中工作?
答案 0 :(得分:2)
正如后面提到的那样,模式匹配不需要防护装置。您可以删除一些多余的案例。
maybe_divide :: Maybe Integer -> Maybe Integer -> Maybe Integer
maybe_divide a b = case (a, b) of
(Just _, Just 0) -> Nothing
(Just n, Just d) -> Just (n `div` d)
_ -> Nothing
但你根本不必写这个功能。因为Maybe是Monad你可以写这个。
maybeDivide :: Integer -> Integer -> Maybe Integer
maybeDivide _ 0 = Nothing
maybeDivide n d = Just (n `div` d)
然后要获得你的Maybe_divide版本,你可以写下来。
maybe_divide' :: Maybe Integer -> Maybe Integer -> Maybe Integer
maybe_divide' a b = a >>= (\n -> b >>= (\d -> maybeDivide n d))
这可能更容易阅读。
maybe_divide'' :: Maybe Integer -> Maybe Integer -> Maybe Integer
maybe_divide'' a b = do
n <- a
d <- b
maybeDivide n d