use*_*033 0 haskell compiler-errors typeerror function-declaration
在Haskell中,我在定义函数时遇到了一些问题,因为我的参数类型与所需类型不匹配.
例如,我想编写一个函数,它接受n :: Int并生成从1到floor平方根的整数列表n.因此我会有一个功能,如:
list :: Int -> [Int]
Run Code Online (Sandbox Code Playgroud)
最初我定义的功能如下:
list :: Int -> [Int]
list n = [1 .. floor (sqrt n)]
Run Code Online (Sandbox Code Playgroud)
当我加载sript时,会出现类型不匹配的错误消息.但是,我不确定我是否不匹配sqrt函数或floor函数的类型.错误消息如下:
No instance for (Floating Int)
arising from a use of 'sqrt' at pe142.hs:6:22-27
Possible fix: add an instance declaration for (Floating Int)
In the first argument of 'floor', namely '(sqrt n)'
In the expression: floor (sqrt n)
In the expression: [1 .. floor (sqrt n)]
Failed, modules loaded: none.
Run Code Online (Sandbox Code Playgroud)
有人可以向我解释导致错误的原因以及如何修复错误吗?
sqrt需要一个Floating类的参数,例如a Double.你传递的是一个Int,这不是一个Floating类的实例- 这就是错误信息告诉你的.
因此,要修复错误,请在调用之前将其转换Int为a .您可以使用该功能.DoublesqrtfromIntegral