我是哈斯克尔的一个新人。这是我的程序:
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)
编译器显示:表达式上下文中的模式语法:_。当我只是在没有防护的情况下使用案例时,它可以工作。为什么它在警卫中不起作用?
如帖子中所述,模式匹配不需要防护装置。您可以删除一些多余的案例。
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
但是您根本不需要编写该函数。因为也许是一个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