这是我的实验室问题之一,我必须写一个maybeDiv
函数,这是我的工作。 Just x y
中有错误,请问导致此错误的原因是什么?感谢。
maybeDiv :: Maybe Integer -> Maybe Integer -> Maybe Integer
maybeDiv mx my = case mx my of
Just x y
| y == 0 -> Just Nothing
| otherwise -> Just (x / y)
Nothing -> Nothing
答案 0 :(得分:1)
你的程序应该看起来像:
maybeDiv :: Maybe Integer -> Maybe Integer -> Maybe Integer
maybeDiv mx my = case (mx, my) of
(Just x, Just y)
| y == 0 -> Nothing
| otherwise -> Just (x / y)
_ -> Nothing
我的电脑目前正在忙着做一个巨大的动画,所以我无法检查。我会稍后检查,除非有人在以前纠正我。
但这不起作用,因为x/y
不是整数。你应该想要一个Double
。所以:
maybeDiv :: Maybe Integer -> Maybe Integer -> Maybe Double
maybeDiv mx my = case (mx, my) of
(Just x, Just y)
| y == 0 -> Nothing
| otherwise -> Just (fromInteger x / fromInteger y)
_ -> Nothing
如果您不允许使用2-tuple (mx,my)
,正如您在评论中所说,您可以这样做:
maybeDiv :: Maybe Integer -> Maybe Integer -> Maybe Double
maybeDiv mx my =
case my of
Nothing -> Nothing
Just 0 -> Nothing
Just y -> case mx of
Nothing -> Nothing
Just x -> Just (fromInteger x / fromInteger y)
如果您想要欧几里德分区的商作为输出,请执行:
maybeDiv :: Maybe Integer -> Maybe Integer -> Maybe Integer
maybeDiv mx my =
case my of
Nothing -> Nothing
Just 0 -> Nothing
Just y -> case mx of
Nothing -> Nothing
Just x -> Just (x `quot` y)
您还可以对该功能进行概括,以便它接受Integer
和Int
类型,如下所示:
maybeDiv :: Integral a => Maybe a -> Maybe a -> Maybe a
maybeDiv mx my =
case my of
Nothing -> Nothing
Just 0 -> Nothing
Just y -> case mx of
Nothing -> Nothing
Just x -> Just (x `quot` y)
答案 1 :(得分:0)
由于这是针对实验室的,因此可能不允许使用Applicative - 但是,为了清楚起见,这是您的功能可能/应该实际的内容:
maybeDiv :: Maybe Int -> Maybe Int -> Maybe Int
maybeDiv ma mb = quot <$> ma <*> mb
这最终会相当于其他答案,但阅读起来会更清晰。