What's the reason of using ; in F# lists instead of ,?
This might be a strange question but if I want to define a list of integers from:
1, 2, 3, 4, 5, 6, 7, 8, 9
Do I need to do it us开发者_开发问答ing the ;
character?
[ 1; 2; 3; 4; 5; 6; 7; 8; 9 ]
instead of?:
[ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
It just seems to me ,
is more natural and easy on the eyes. Just wondering the idea behind using ;
? (Not criticizing)
Yes you must. The reason why is that in F# the comma operator is used for tuple expressions. So the expression 1,2,...9
is interpreted as a single tuple with 9 values.
[1,2] // List with 1 element that is a tuple value - (int*int) list
[1;2] // List with 2 elements that are integer values - int list
Other answers have pointed out the main reason.
As an aside it is worth noting that, like most other places that semicolon is used in the language, an alternative is a newline. For example
[ "foo"; "bar"; "baz" ]
can also be written as
[ "foo"
"bar"
"baz" ]
or a variety of other layouts where semicolons are replaced by newlines.
[1,2,3,4,5]
is a list of 1 element of type int * int * int * int * int
[1;2;3;4;5]
is a list of 5 elements of type int
also, list comprehensions and ranges are your friends
let bar = [1..9]
, 1..9 is a range so it get's unfolded into 1;2;3;...9;
let blort = [for i in 1..9 -> i]
is a comprehension that does the same thing -- a little more power for some performance issues.
Edit: for completeness sake, you can also do
let foo = [1
2
3]
and get a list of [1;2;3]
Just wondering the idea behind using ;?
Tuples are more common in ML and using ;
lets you write lists of tuples as:
[1, 2; 3, 4]
Historically, F# inherited this syntax from OCaml which created its syntax by trying to remove more superfluous parentheses from Standard ML syntax.
精彩评论