10

我还是新手,正在尝试创建一个用于函数的列表,并希望它尽可能小,恰好是 logBase x y。但我无法将 logBase 纳入我可以在此列表中使用的内容。

[1 .. (logBase xy)]

有什么建议么?

4

3 回答 3

10

你没有发布你得到的类型错误,但我想它是这样的:

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)]

问题是:

Prelude> :t logBase
logBase :: (Floating a) => a -> a -> a

在 Floating 类中返回一个类型,而程序中的其他变量 (1, 'x', 'y') 是整数类型。

我想你想要一个整数序列?

Prelude> :set -XNoMonomorphismRestriction
Prelude> let x = 2
Prelude> let y = 42
Prelude> [1 .. truncate (logBase x y)] 
[1,2,3,4,5]

使用 truncate、celing 或 floor。

于 2009-09-09T10:42:52.573 回答
8

您可能需要这里的功能列表之一。 HoogleHayoo!是处理这类事情的好工具,因为它们可以让你输入你想要的函数类型并返回函数列表。借助 Haskell 丰富的类型系统,这可能是一个非常有用的工具,比动态类型语言甚至像 C 或 Java 这样的静态类型语言更有用。

于 2009-09-09T02:54:31.477 回答
2

您可能需要某种舍入、截断、下限或上限函数。Ints 和 Floats 是不同的类型(如您所见),编译器不会让您混合使用它们。我会在一分钟内找到参考。

于 2009-09-09T02:12:32.417 回答