在学习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
两个问题:
show
next 7
的结果?答案 0 :(得分:1)
我相信Collatz序列是一个整数序列,因此不需要将结果作为分数。
next :: (Integral a) => a -> a
为了能够从除法中获取整数,您应该使用div
函数。请注意,除非您只划分偶数,否则除法总是精确的:
next x
| odd x = x * 3 + 1
| otherwise = x `div` 2