Haskell代码zipWith使用Maybe

Tib*_*doš 3 haskell

我在使用此代码时遇到问题.我正在尝试编写一个简单的函数,它接受两个列表并尝试通过列表B的相应元素划分列表A的每个元素.如果列表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) 
Run Code Online (Sandbox Code Playgroud)

这可能是愚蠢的,但我根本找不到它.

编辑:这是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.
Run Code Online (Sandbox Code Playgroud)

编辑2:使用div x y而不是x / y只是做它.:) 谢谢.

dka*_*sak 7

您正在为Integral函数指定约束,但(/)在函数内部使用表示小数除法的函数.

您可能想要使用div,这是整体划分,例如3 `div` 2 == 1.否则,将约束更改IntegralFractional(这是错误消息告诉您要执行的操作).