如何处理Haskell中的类型

hab*_*min 1 haskell types

我已经开始学习Haskell了,而且我一直在读"为了大好学习你是一个Haskell".我读完了模块章节的一半.一位朋友向我展示了代码战,我决定将我学到的一些内容用于测试.

我正在尝试创建一个函数,该函数返回给定Integral是否为4的幂的布尔值.这是代码.

module PowerOfFour where

isWhole n = fromIntegral (round n) == n

isPowerOf4 :: Integral n => n -> Bool
isPowerOf4 4 = True
isPowerOf4 x = if x < 4 then
    False
else
    if isWhole (x / 4) then
    isPowerOf4 (truncate (x / 4))
  else
    False
Run Code Online (Sandbox Code Playgroud)

这是我收到的错误消息.

/tmp/haskell11524-8-kke52v/PowerOfFour.hs:10:12:
    Could not deduce (RealFrac n) arising from a use of `isWhole'
    from the context (Integral n)
      bound by the type signature for
                 isPowerOf4 :: Integral n => n -> Bool
      at /tmp/haskell11524-8-kke52v/PowerOfFour.hs:5:15-37
    Possible fix:
      add (RealFrac n) to the context of
        the type signature for isPowerOf4 :: Integral n => n -> Bool
    In the expression: isWhole (x / 4)
    In the expression:
      if isWhole (x / 4) then isPowerOf4 (truncate (x / 4)) else False
    In the expression:
      if x < 4 then
          False
      else
          if isWhole (x / 4) then isPowerOf4 (truncate (x / 4)) else False

/tmp/haskell11524-8-kke52v/PowerOfFour.hs:10:23:
    Could not deduce (Fractional n) arising from a use of `/'
    from the context (Integral n)
      bound by the type signature for
                 isPowerOf4 :: Integral n => n -> Bool
      at /tmp/haskell11524-8-kke52v/PowerOfFour.hs:5:15-37
    Possible fix:
      add (Fractional n) to the context of
        the type signature for isPowerOf4 :: Integral n => n -> Bool
    In the first argument of `isWhole', namely `(x / 4)'
    In the expression: isWhole (x / 4)
    In the expression:
      if isWhole (x / 4) then isPowerOf4 (truncate (x / 4)) else False
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

我在isWhole中使用fromIntegral来修复类似的错误,并且isWhole现在可以单独使用.但是,我似乎无法摆脱isPowerOf4中的这些错误.我已经尝试过GHC提供的可能修复程序,但我可能没有做到这一点.

我宁愿保留isPowerOf4函数的类型签名,因为这是由代码新闻提供的,所以我猜它是一个要求.

Jer*_*ist 5

在Haskell中,/运算符是分数类型而不是整数类型.对于你应该使用的整数类型div(你可以通过在反引号中包围它来使用它的中缀).您也可以使用modrem查找剩余部分,例如%典型语言(负数不同)

isPowerOf4 :: Integral n => n -> Bool
isPowerOf4 4 = True
isPowerOf4 x = if x < 4
  then False
  else
    if x `mod` 4 == 0
      then isPowerOf4 (x `div` 4)
      else False
Run Code Online (Sandbox Code Playgroud)