Haskell代码zipWith使用Maybe
我的代码有问题。我正在尝试编写一个简单的函数,它包含两个列表,并尝试将列表a的每个元素除以列表B的相应元素。如果列表B中的元素为0,它应该返回Haskell代码zipWith使用Maybe,haskell,Haskell,我的代码有问题。我正在尝试编写一个简单的函数,它包含两个列表,并尝试将列表a的每个元素除以列表B的相应元素。如果列表B中的元素为0,它应该返回Nothing,否则它应该返回Just(a/B) 代码如下: divlist :: Integral a => [a] -> [a] -> [Maybe a] divlist = zipWith (\x y -> if (y /= 0) then Just (x / y) else Nothing) 这可能是件愚蠢的事,但我就是
Nothing
,否则它应该返回Just(a/B)
代码如下:
divlist :: Integral a => [a] -> [a] -> [Maybe a]
divlist = zipWith (\x y -> if (y /= 0) then Just (x / y) else Nothing)
这可能是件愚蠢的事,但我就是找不到
编辑:这是ghci报告的内容:
C:\Users\spravce\Desktop\Haskell\6.hs:16:51: error:
• Could not deduce (Fractional a) arising from a use of ‘/’
from the context: Integral a
bound by the type signature for:
divlist :: Integral a => [a] -> [a] -> [Maybe a]
at C:\Users\spravce\Desktop\Haskell\6.hs:14:1-48
Possible fix:
add (Fractional a) to the context of
the type signature for:
divlist :: Integral a => [a] -> [a] -> [Maybe a]
• In the first argument of ‘Just’, namely ‘(x / y)’
In the expression: Just (x / y)
In the expression: if (y /= 0) then Just (x / y) else Nothing
Failed, modules loaded: none.
编辑2:
使用
div x y
而不是x/y
就这样做了。:)谢谢。您在函数上指定了一个积分约束,但在函数内部使用了(/)
,表示分数除法
您可能想使用div
,它是整数除法,例如3`div`2==1
。否则,将约束从整数
更改为分数
(这就是错误消息告诉您要执行的操作)