由于使用"打印"而产生的模棱两可的类型变量"a0"?



在学习haskell时,我正在尝试编写一个给定数字的函数,该函数将在collatz序列中赋予其继任者:

next :: (Fractional a, Integral a) => a -> a
next x
    | odd x = x * 3 + 1
    | otherwise = x / 2

当我运行next 7时,我会得到:

<interactive>:150:1: error:
* Ambiguous type variable `a0' arising from a use of `print'
  prevents the constraint `(Show a0)' from being solved.
  Probable fix: use a type annotation to specify what `a0' should be.
  These potential instances exist:
    instance Show Ordering -- Defined in `GHC.Show'
    instance Show Integer -- Defined in `GHC.Show'
    instance Show a => Show (Maybe a) -- Defined in `GHC.Show'
    ...plus 22 others
    ...plus 12 instances involving out-of-scope types
    (use -fprint-potential-instances to see them all)
* In a stmt of an interactive GHCi command: print it

两个问题:

  1. 我是否在签名中使用最佳类约束?
  2. 假设我是show next 7的结果?

我相信collatz序列是整数序列,因此无需将结果分数。

next :: (Integral a) => a -> a

要能够从一个部门获得整数,您应该使用div函数。请注意,当您仅分配均匀的数字时,分区将始终是准确的:

next x
    | odd x = x * 3 + 1
    | otherwise = x `div` 2

最新更新