我想每 0.1
做一个数字列表来自 -150
至 150
.
为此,我创建了一个列表,然后尝试将分数乘法 lambda 映射到它上面,如下所示:
let indices = [-1500,-1499..1500]
let grid = map (\x -> 0.1 *x) indices
这让ghci吐出一个错误。
另一方面,这两个都可以正常工作:
let a = 0.1*2
和
let grid = map (\x -> 2 *x) indices
这里发生了什么?为什么 Num 乘以分数只会在应用于带有 map 的列表时失败?
编辑:
我得到的错误是:
No instance for (Fractional Integer)
arising from the literal `0.1'
Possible fix: add an instance declaration for (Fractional Integer)
In the first argument of `(*)', namely `0.1'
In the expression: 0.1 * x
In the first argument of `map', namely `(\ x -> 0.1 * x)'
最佳答案
您已经发现了“可怕的单态限制”。基本上 GHC 会推断 indices
的类型成为像 [Integer]
这样的单一类型而不是 Num a => a
.您可以提供类似 indices :: [Float]
的注释。 ,或重新定义您的定义以避免限制。
例如(不是建议),如果你让 indices
一个函数:let indices a = [-1500, -1499..1500]
,推断的类型现在是 (Enum t, Num t) => a -> [t]
. a
参数未使用但违反了限制。然后你就可以做 map f (indices whatever)
.在 Haskell Wiki 中查看更多关于 Monomorphism Restriction 的信息。 .
关于haskell - 为什么我不能将乘以分数的函数映射到 Nums 列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15803386/