Haskell将Float转换为Int [英] Haskell converting Float to Int
问题描述
我还是个新手,试图创建一个在函数中使用的列表,并希望保持它尽可能小,这恰好是logBase x y。
,但是我无法将logBase转换成我可以在这个列表中使用的东西。
$ b [1 ..(logBase xy)]
有什么建议?
我想这是这样的:
Prelude>让x = 2
前奏>让y = 7
前奏> [1 ..(logBase xy)]
< interactive>:1:7:
使用'logBase'时没有(浮点整型)
的实例< interactive>:1:7-17
可能的修正:为(浮动整数)
添加实例声明在表达式中:(logBase xy)
在表达式中:[1 .. (logBase xy)]
在`it'的定义中:it = [1 ..(logBase xy)]
问题在于:
Prelude> :t logBase
logBase ::(Floating a)=> a - > a - >一个
在Floating类中返回一个类型,而在你的程序中其他变量(1,'x' ,'y')是整型。
我假设你想要一个整数序列吗?
前奏> :set -XNoMonomorphismRestriction
Prelude>让x = 2
前奏>让y = 42
前奏> [1 .. truncate(logBase xy)]
[1,2,3,4,5]
使用truncate,celing或floor。
I'm still new and trying to create a list for use in a function and want to keep it as small as possible which happens to be logBase x y. but I'm having trouble getting logBase into something I can use in this list.
[1 .. (logBase x y)]
Any suggestions?
You don't post what type error you get, but I imagine it is something like this:
Prelude> let x = 2
Prelude> let y = 7
Prelude> [1 .. (logBase x y)]
<interactive>:1:7:
No instance for (Floating Integer)
arising from a use of `logBase' at <interactive>:1:7-17
Possible fix: add an instance declaration for (Floating Integer)
In the expression: (logBase x y)
In the expression: [1 .. (logBase x y)]
In the definition of `it': it = [1 .. (logBase x y)]
The problem is that:
Prelude> :t logBase
logBase :: (Floating a) => a -> a -> a
returns a type in the Floating class, while other variables in your program (1, 'x', 'y') are of integral type.
I presume you want a sequence of Integers?
Prelude> :set -XNoMonomorphismRestriction
Prelude> let x = 2
Prelude> let y = 42
Prelude> [1 .. truncate (logBase x y)]
[1,2,3,4,5]
Use truncate, celing or floor.
这篇关于Haskell将Float转换为Int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!