我有以下函数返回给定数字的因子对
factorPairs:: (RealFrac a, Floating a, Integral a) => a -> [(a, a)]
factorPairs n = map(\x -> (x, div n x)) [y | y <- [1..(ceiling $ sqrt n)], n `rem` y == 0]
当我在 ghci 中调用该函数时factorPairs 18
我收到运行时错误
* Ambiguous type variable `a0' arising from a use of `it'
prevents the constraint `(Floating a0)' from being solved.
Probable fix: use a type annotation to specify what `a0' should be.
These potential instances exist:
instance Floating Double -- Defined in `GHC.Float'
instance Floating Float -- Defined in `GHC.Float'
* In the first argument of `print', namely `it'
In a stmt of an interactive GHCi command: print it
我可以在 ghci 中对该函数进行硬编码
map(\x -> (x, div 18 x)) [y | y <- [1..(ceiling $ sqrt 18)], 18 `rem` y == 0]
并且没有任何问题,但我似乎无法弄清楚为什么我的功能失败。我相信 ghci 试图告诉我它无法弄清楚要调用什么类型print
但我正在努力寻找解决方案。
这与 Haskell 中数字文字的重载有关。当您输入时map(\x -> (x, div 18 x)) [y | y <- [1..(ceiling $ sqrt 18)], 18 `rem` y == 0]
into ghci
, the 18
这是一个论据sqrt
默认为Double
和其他人Integer
s.
然而,当你写
factorPairs:: (RealFrac a, Floating a, Integral a) => a -> [(a, a)]
factorPairs n = map(\x -> (x, div n x)) [y | y <- [1..(ceiling $ sqrt n)], n `rem` y == 0]
你强制所有实例n
只有一种类型。然后,问题就变成了根本不存在满足所有这些约束的默认数字类型(实际上我认为通常是数字类型),因此 GHC 会告诉您它尝试的“可能的实例”。解决方案是添加fromIntegral
并放宽约束:
factorPairs:: Integral a => a -> [(a, a)]
factorPairs n = map(\x -> (x, div n x)) [y | y <- [1..(ceiling $ sqrt $ fromIntegral n)], n `rem` y == 0]
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)