gpt4 book ai didi

haskell - 分数整数错误 [haskell]

转载 作者:行者123 更新时间:2023-12-04 04:36:38 25 4
gpt4 key购买 nike

No instance for (Fractional Int) arising from a use of `leap'
Possible fix: add an instance declaration for (Fractional Int)
In the first argument of `(==)', namely `leap (x)'
In the second argument of `(&&)', namely `leap (x) == 1'
In the expression: (y == 2) && leap (x) == 1

在 ghci 中加载文件时出现此错误

这是导致错误的函数
daysInMonth :: Int -> Int -> Int
daysInMonth y x
| (y == 1 || y == 3 || y == 5 || y == 7 || y == 8 || y == 10 || y == 12) = 31
| (y == 4 || y == 6 || y == 9 || y == 11) = 30
| (y == 2) && leap(x) == 1 = 28
| (y == 2) && leap(x) == 0 = 29
where
leap a = if (a / 4) == 0 then return 1 else return 0

最佳答案

您正在尝试计算 a / 4哪里a (它只等于 x ,一个 Int )是一个 Int . Int类型不属于Fractional类型类,因此 /未为 Int 定义s。为了做你想做的事,你可以:

  • 转换 aFractional通过书写输入 if fromIntegral a / 4 == 0 then ...
  • 或者,如果你想做“整数除法”并丢弃余数,写 if quot a 4 == 0 then ...

  • 另外, return在 Haskell 中不像 return其他语言。摆脱它在这里。

    (还有, that's not how you determine leap years。)

    关于haskell - 分数整数错误 [haskell],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19644968/

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