Use list cons operator (a :: b) as a function

℡╲_俬逩灬. 提交于 2019-12-01 02:28:05
Brian

Paraphrased from http://cs.hubfs.net/forums/permalink/11713/11713/ShowThread.aspx#11713

(::) is a discriminated union 'constructor' for the list<'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.

let cons x y = x :: y

and use cons, or just use a lambda fun x y -> x::y, if you want a "curried prefix function of two args" for this.

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 (<@ @>)).

:: and [] can both be represented by List<_>.Cons and List<_>.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#.

> List.Cons(4, List.Empty);;
val it : int list = [4]

> 4::[];;
val it : int list = [4]

> List<int>.Cons(4, List<int>.Empty);;
val it : int list = [4]

> List.Cons;;
val it : 'a * 'a list -> 'a list = <fun:clo@24-7> //'

> List<int>.Empty;;
val it : int list = []
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!