如何编写没有参数的Haskell函数?

3

我有一个函数声明叫做e6。我需要将其中的undefined替换为一些代码并使其正常工作。

e6 :: Int -> Int -> Int
e6 = undefined

我知道例如

add :: Int -> Int -> Int
add a b = a + b

这个函数需要参数 a 和 b,然后返回 a + b。但是如何编写一个不需要参数的函数呢?我尝试了:

e6 :: Int -> Int -> Int
e6 = 2 + 3

并显示了以下内容:

由于使用“+”而引发无法获取(Int -> Int -> Int)的Num实例。


5
你的意思是希望它忽略两个参数吗? - Ry-
1
那是一个常量,所以 e6 = 2 + 3,签名为 Int - Willem Van Onsem
2个回答

11

现在不是很清楚需要什么样的修复措施,因为我并不确定你想要的具体内容。以下是可能的解释。

  • You want e6 to be equivalent to the constant 5, computed by evaluating 2+3. Since this is not a function, you should not use a function type in its signature.

    e6 :: Int
    e6 = 2 + 3
    
  • You want e6 to be a function just like add is, but to always return 2+3 instead of a+b -- that is, to ignore its arguments, even though it still has them. Then the type signature is okay, but you need to explicitly ignore the arguments.

    e6 :: Int -> Int -> Int
    e6 _ _ = 2 + 3
    -- OR
    e6 a b = 2 + 3
    
  • You want e6 to be just like add in every way, but you don't want to explicitly name its arguments when defining e6. Then, if you're not giving the arguments to e6, you also can't give the arguments to +. So:

     e6 :: Int -> Int -> Int
     e6 = (+)
    

    (+) is special syntax for turning an infix operator into a prefix function; roughly, \a b -> (+) a b and \a b -> a + b behave the same way.


抱歉我的描述不太好。但是这对我帮助很大。非常感谢。 - H. Dong
我认为值得指出的是,Haskell 是惰性求值的,因此在某种意义上,像 e = 2 + 3 这样的变量确实表现得像一个不带参数的函数,计算 2 + 3 - Kwarrtz
1
“(+)”真的被称为“section syntax”吗?我认为只有“(+ exp)”和“(exp +)”才是sections。 - chi
你可能是对的。为了避免说谎,我现在把它放在一边了——无论如何,它的名称对于这个答案的目的来说并不重要。 - Daniel Wagner

4

您是否想了解如何以无参形式编写函数?

如果是的话,您可以将加法函数编写为:

e6 = (+)

在这个简单的例子中,e6 只是成为了 + 运算符的别名。在 Haskell 中,运算符只是带有特殊名称的函数,当您想将它们用作函数而不是运算符时,可以像上面那样用括号括起来。(+) 函数(即 + 运算符)已经是一个接受两个参数并返回值的函数。
以下是与之交互的 GHCi 示例:
Prelude> :t e6
e6 :: Num a => a -> a -> a
Prelude> e6 1 3
4
Prelude> e6 42 1337
1379

推断出的类型是 Num a => a -> a -> a,但也兼容于 Int -> Int -> Int,所以如果您想要将类型限制为此,则可以使用更为严格的类型声明函数。不过,没有特别的理由需要这样做,因为通用版本同样适用于 Int,如 GHCi 会话所示。

非常好的解释!非常感谢! - H. Dong

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接