简体   繁体   English

为什么此Haskell类型的强制转换无法编译?

[英]Why won't this Haskell type coercion compile?

Ugh. 啊。 The following code fails to compile: 以下代码无法编译:

factorsOf number = [(x, quot number x) | x <- [2..toInteger $ floor $ sqrt number], number `mod` x == 0]

The following error is thrown: 引发以下错误:

  • "No instance for (Floating Integer) arising from a use of `sqrt'" “没有因使用'sqrt'而引起的(Floating Integer)实例”

Please help? 请帮忙? I'm clearly not grokking Haskell coercion. 我显然不是在嘲笑Haskell的强制。

PS: Leaving off toInteger compiles but throws a type-ambiguity error at runtime. PS:离开toInteger编译,但在运行时引发类型歧义错误。

It is highly advisable to always start design of a Haskell function with the type signature , and only then write the implementation. 强烈建议始终以类型签名开始设计Haskell函数,然后再编写实现。 In this case, you probably want 在这种情况下,您可能想要

factorsOf :: Integer -> [(Integer, Integer)]

So, within factorsOf n = ... , the variable n will have type Integer . 因此,在factorsOf n = ... ,变量n将具有Integer类型。 That's the problem: you're trying to take the square root of an integer, but sqrt is only defined on floating numbers. 这就是问题所在:您试图获取整数的sqrt ,但sqrt仅在浮点数上定义。 So you need to convert to such a number before taking the root. 因此,您需要先转换成这样的数字, 然后再取根。 After the root, you'll then want to truncate back to an integer, but floor already does that. 在根之后,您将要截断为整数,但是floor已经做到了。 toInteger is not needed. toInteger

factorsOf :: Integer -> [(Integer, Integer)]
factorsOf n
     = [ (x, n`quot`x)
       | x <- [2 .. floor . sqrt $ fromIntegral n]
       , n `mod` x == 0
       ]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM