使用列表 cons 运算符 (a :: b) 作为函数
F# 允许您通过使用 (
)
将运算符转换为函数:例如,(+)
的类型为 int -> ;整数-> int
。
是否可以使用列表 cons 运算符 ::
来做到这一点?
它的行为与普通的二元运算符不同:
FSI> (::);;
(::);;
-^^
c:\temp\stdin(3,2): error FS0010: Unexpected symbol '::' in expression.
Expected ')' or other token.
List.Cons
方法采用一个元组;它不是咖喱。
(能够做到这一点非常有用。例如,您可以使用它来实现以折叠方式进行映射< /a>)。
F# lets you turn operators into functions by surrounding them with (
)
: for instance, (+)
is of type int -> int -> int
.
Is it possible to do this with the list cons operator, ::
?
It doesn't behave like a normal binary operator:
FSI> (::);;
(::);;
-^^
c:\temp\stdin(3,2): error FS0010: Unexpected symbol '::' in expression.
Expected ')' or other token.
And the List.Cons
method takes a tuple; it's not curried.
(It's useful to be able to do this. For instance, you can use it to implement map in terms of fold).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
转述自 http://cs.hubfs.net/forums/ permalink/11713/11713/ShowThread.aspx#11713
(::)
是list<'a> 的可区分联合“构造函数” type
,因此提出了一个问题:作为函数值,其参数是否应该柯里化(如+
)或元组(如所有 DU 构造函数)。对于某些人来说,无论哪种方式都显得可疑/出乎意料,因此 F# 根本不允许这种构造。当然,您始终可以编写 eg
并使用 cons,或者仅使用 lambda fun xy -> x::y,如果你想要一个“两个参数的柯里化前缀函数”。
Paraphrased from http://cs.hubfs.net/forums/permalink/11713/11713/ShowThread.aspx#11713
(::)
is a discriminated union 'constructor' for thelist<'a> type
, and so raised the question of whether as a function value its arguments should be curried (like+
) or tupled (like all DU constructors). Either way seems fishy/unexpected to some people, so F# simply disallows the construct.Of course you can always write e.g.
and use
cons
, or just use a lambdafun x y -> x::y
, if you want a "curried prefix function of two args" for this.不幸的是,不,你不能。
::
不是运算符,而是根据语言语法的“符号关键字”(请参阅 3.6 规范),:?>
和其他一些也是如此。不过,这里的语言似乎并不完全一致,因为有一些符号关键字可以被视为运算符(至少(*)
和(<@ @ >)
)。Unfortunately, no, you can't.
::
is not an operator, but a "symbolic keyword" according to the language grammar (see section 3.6 of the spec), as are:?>
and a few others. The language doesn't seem completely consistent here, though, since there are a few symbolic keywords which can be treated as though they were operators (at least(*)
and(<@ @>)
).::
和[]
都可以用List<_>.Cons
和List<_>.Empty
表示> 分别。请记住,前者将元组作为参数。这些列表位于此处,以便可以使用 F# 以外的语言创建列表。::
and[]
can both be represented byList<_>.Cons
andList<_>.Empty
respectively. Keep in mind though that the former takes a tuple as an argument. These are here so lists can be created in languages other than F#.