呃。以下代码编译失败:
factorsOf number = [(x, quot number x) | x <- [2..toInteger $ floor $ sqrt number], number `mod` x == 0]
抛出以下错误:
- “(Floating Integer) 没有因使用 `sqrt' 而产生的实例”
请帮忙?我显然不是在摸索 Haskell 强制转换。
PS:离开 toInteger
编译但在运行时抛出类型歧义错误。
最佳答案
强烈建议始终使用类型签名 开始设计 Haskell 函数,然后才编写实现。在这种情况下,您可能想要
factorsOf :: Integer -> [(Integer, Integer)]
因此,在 factorsOf n = ...
中,变量 n
的类型为 Integer
。这就是问题所在:您试图对整数求平方根,但 sqrt
仅在 float 上定义。所以你需要在取根之前转换成这样的数字。在根之后,您会想要截断回一个整数,但是 floor
已经这样做了。不需要 toInteger
。
factorsOf :: Integer -> [(Integer, Integer)]
factorsOf n
= [ (x, n`quot`x)
| x <- [2 .. floor . sqrt $ fromIntegral n]
, n `mod` x == 0
]
关于haskell - 为什么这个 Haskell 类型的强制转换不能编译?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53943183/