分数Int误差[haskell]

时间:2013-10-28 20:58:57

标签: haskell

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

1 个答案:

答案 0 :(得分:3)

您正在尝试计算a / 4 a(其中x只有IntInt)是IntFractional类型不属于/类型类,因此Int未定义a。为了做你想做的事,你可以:

  1. 通过撰写Fractional

  2. if fromIntegral a / 4 == 0 then ...转换为if quot a 4 == 0 then ...类型
  3. 或者,如果您想进行“整数除法”并丢弃余数,请写下return

  4. 此外,Haskell中的return与其他语言中的{{1}}不同。在这里摆脱它。

    (另外,that's not how you determine leap years。)