gpt4 book ai didi

使用 Maybe 的 Haskell 代码 zipWith

转载 作者:行者123 更新时间:2023-12-02 12:13:14 26 4
gpt4 key购买 nike

我在使用这段代码时遇到了问题。我正在尝试编写一个简单的函数,它接受两个列表,并尝试将列表 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 就可以了。 :) 谢谢。

最佳答案

您正在对函数指定Integral 约束,但在函数内部使用(/) 表示分数除法。

您可能想使用 div,它是整数除法,例如3 `div` 2 == 1。否则,将约束从Integral更改为Fractional(这是错误消息告诉您要做的事情)。

关于使用 Maybe 的 Haskell 代码 zipWith,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40321358/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com