【发布时间】:2016-11-02 01:31:04
【问题描述】:
我使用 Haskell 已经有一段时间了,但在使用数值类型时遇到了一些问题。大多数时候我可以在尝试一下之后解决,但这次我被这段微不足道的代码难倒了两个多小时。
我有这些功能:
takeLessEqual x = takeWhile (<=x)
leftHalf x = takeLessEqual x $ (map (\x -> ((x+0.5)*(x+0.5) + 0.75))) [1..]
-- Produces the list [3.0,7.0,13.0,21.0,31.0,43.0 ... (some number < x)]
rightHalf x = takeLessEqual x $ (map (\x -> if even x then x*x + 1 else x*x)) [1..]
-- Produces the list [1,5,9,17,25,37,49 ... (some number < x)]
total x = (sum $ rightHalf x) + (sum $ leftHalf x)
-- total 10 Should produce some number 25 or 25.0
它加载到 ghci 时没有错误,但是当我尝试评估时:
*> leftHalf 10
[3.0,7.0]
it :: (Ord a, Fractional a, Enum a) => [a]
*> rightHalf 10
[1,5,9]
it :: Integral a => [a]
*> total 10
<interactive>:150:1: error:
• Ambiguous type variable ‘a0’ arising from a use of ‘it’
prevents the constraint ‘(Fractional a0)’ from being solved.
Probable fix: use a type annotation to specify what ‘a0’ should be.
These potential instances exist:
instance Fractional Double -- Defined in ‘GHC.Float’
instance Fractional Float -- Defined in ‘GHC.Float’
...plus one instance involving out-of-scope types
(use -fprint-potential-instances to see them all)
• In the first argument of ‘print’, namely ‘it’
In a stmt of an interactive GHCi command: print it
我已经尝试在不同点添加类型注释并使用 toInteger 和 fromIntegral 转换类型,但没有成功。
我做错了什么,我该如何解决?
【问题讨论】:
-
试试:
total 10 :: Double -
我已经尝试过这个 ofc --> • 没有使用 'total' 产生 (Integral Double) 的实例 • 在表达式中:total 10 :: Double 在 'it' 的等式中:它 = 总共 10 :: 双倍
-
是的,问题是Haskell没有任何类型同时是
Integral和Fractional,但是你的total函数需要这样的类型! -
fwiw,您可以将
leftHalf重写为leftHalf x = takeLessEqual x $ map (\x -> (x * x + x + 1) [1..],它适用于所有数字类型,而不仅仅是Integral或Fractional类型。
标签: haskell