模糊类型变量`a0'使用'print'?

时间:2017-03-03 07:04:58

标签: haskell

在学习Haskell时,我试图编写一个给定数字的函数,将其Collatz sequence的后继者:

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的结果?

1 个答案:

答案 0 :(得分:1)

我相信Collat​​z序列是一个整数序列,因此不需要将结果作为分数。

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

为了能够从除法中获取整数,您应该使用div函数。请注意,除非您只划分偶数,否则除法总是精确的:

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