Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/haskell/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Haskell代码zipWith使用Maybe_Haskell - Fatal编程技术网

Haskell代码zipWith使用Maybe

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) 这可能是件愚蠢的事,但我就是

我的代码有问题。我正在尝试编写一个简单的函数,它包含两个列表,并尝试将列表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) 
这可能是件愚蠢的事,但我就是找不到

编辑:这是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
。否则,将约束从
整数
更改为
分数
(这就是错误消息告诉您要执行的操作)