haskell:这段代码出了什么问题

时间:2017-08-07 18:14:58

标签: haskell

我正在尝试编译这段代码,但它不起作用而且我没有得到它:

division :: Maybe Int -> Maybe Int -> Maybe Int
division _ (Maybe 0) = Nothing
division (Maybe a) (Maybe b) = Just (a `div` b)

2 个答案:

答案 0 :(得分:2)

Maybe a定义为:

data Maybe a = Just a | Nothing

因此无法将Maybe a 置于功能定义中,只能在签名中使用

division :: Maybe Int -> Maybe Int -> Maybe Int
division _ (Just 0) = Nothing
division (Just a) (Just b) = Just (a `div` b)

此外,函数 not total :并非所有可能的输入都由函数处理,因此这可能导致异常。所以你最好在这些情况下返回一些东西(通常一个返回Nothing):

division :: Maybe Int -> Maybe Int -> Maybe Int
division _ (Just 0) = Nothing
division (Just a) (Just b) = Just (a `div` b)
division _ _ = Nothing

最后,我们可以使用Integral i作为类型,而不是Int,并使函数更通用:

division :: Integral i => Maybe i -> Maybe i -> Maybe i
division _ (Just 0) = Nothing
division (Just a) (Just b) = Just (a `div` b)
division _ _ = Nothing

答案 1 :(得分:1)

基于Daniel Wagner的评论和Willem Van Onsem关于Integral的观点,这就是我写这个函数的方法:

division :: Integral a => a -> a -> Maybe a
division _ 0 = Nothing
division p q = Just (div p q)

要将其与Maybe参数一起使用,您只需编写

即可
division <$> m <*> n

或等同地

liftA2 division m n

其中liftA2位于Control.Applicative