[英]How fst on function that output tuples works in Haskell?
I'm trying to figure out how tuples work in Haskell, and how you can get certain data values from tuples. 我试图找出元组在Haskell中如何工作,以及如何从元组中获取某些数据值。
I have the following code, and this runs properly, and prints out the tuple output I expect: 我有以下代码,这运行正常,并打印出我期望的元组输出:
test :: Integer -> (Integer, Integer)
test c = function(1, c)
However, when I try to get just the first value from the tuple, as shown below, 但是,当我尝试从元组中获取第一个值时,如下所示,
test :: Integer -> Integer
test c = fst function(1, c)
I get the following error 我收到以下错误
Any help or advice would be appreciated. 任何帮助或建议将不胜感激。 Thanks in advance.
提前致谢。
You simply got the syntax wrong. 你只是弄错了语法。
fx
means " apply (call) function f
to argument x
". fx
表示“ 将(调用)函数f
应用于参数x
”。
Similarly, fxy
means "apply function f
to arguments x
and y
". 类似地,
fxy
表示“将函数f
应用于参数x
和y
”。
Your example function(1, c)
means " apply function function
to argument (1, c)
". 您的示例
function(1, c)
表示“ 将函数function
应用于参数(1, c)
”。 Don't let the absence of a space before the opening paren fool you: (1, c)
does not mean " call function with two arguments " (as it would in, say, C or Java), it means " make a pair with two components, 1
and c
". 不要让开头之前没有空格让你愚弄:
(1, c)
并不意味着“ 用两个参数调用函数 ”(就像在C或Java中那样),它意味着“ 做一对有两个组成部分, 1
和c
“。 This pair is then used as a single argument for function
. 然后将该对用作
function
的单个参数。
Now, the next expression, fst function (1, c)
means " apply function fst
to two arguments - function
and (1, c)
". 现在,下一个表达式,
fst function (1, c)
意味着“ 将函数fst
应用于两个参数 - function
和(1, c)
”。 This is obviously not what you meant. 这显然不是你的意思。 Instead, you meant to first call
function
with argument (1, c)
, and then pass the result as argument to fst
. 相反,你打算先用参数
(1, c)
调用function
,然后将结果作为参数传递给fst
。 To express this, you may use parentheses: 要表达这一点,您可以使用括号:
test c = fst (function (1, c))
But of course this is now too many parentheses. 但当然现在这个括号太多了。 To avoid the extra pair, you may use the ubiquitous operator
$
: 为避免额外的对,您可以使用无处不在的运算符
$
:
test c = fst $ function (1, c)
This operator doesn't really do anything interesting, it just applies the function on the left to the argument on the right: 这个运算符并没有真正做任何有趣的事情,它只是将左边的函数应用到右边的参数:
f $ x = f x
The value of this operator is that it makes it possible for the function application to not have the highest precedence, and thus get rid of extra parentheses. 此运算符的值是,它使函数应用程序不具有最高优先级,从而省去了额外的括号。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.