F#: What is the difference between [0; 1; 2; 3; 4; 5] and [0, 1, 2, 3, 4, 5]?

f#, list

Solution

In F#, a comma is a delimiter for a tuple.

So when you see something like this:

match x, y with
| 1.1, 2.2 -> doSomething()
| 2.2, 3.3 -> doSomethingElse()
| _ -> defaultAction()

that is shorthand for

match (x, y) with
| (1.1, 2.2) -> doSomething()
| (2.2, 3.3) -> doSomethingElse()
| _ -> defaultAction()

So in fact your array `[0, 1, 2, 3, 4, 5]` contains only one element: the tuple `(0, 1, 2, 3, 4, 5)`. To verify this, try doing this quick test in your REPL:

let test = ([0, 1, 2, 3, 4, 5] = [(0, 1, 2, 3, 4, 5)])

ADDENDUM

In fact, the F# Interactive window is a very good tool for answering similar questions. As well as the test above, you can also simply highlight the following lines and hit Ctrl+Enter:

let value1 = [0; 1; 2; 3; 4; 5]
let value2 = [0, 1, 2, 3, 4, 5]

The output is

val value1 : int list = [0; 1; 2; 3; 4; 5]
val value2 : (int * int * int * int * int * int) list = [(0, 1, 2, 3, 4, 5)]

which answers the question very succinctly. True to the nature of F#, it reproduces my long-winded answer in two lines.

Problem

I know how to make a list: ``` let f n = let out_listA = [ 0 .. (n - 1) ] let out_list = out_listA |> List.reduce (fun state item -> state + ", " + item) out_list ``` I am working with on-line exercises that involving printing something that looks like the following if `n = 5`. ``` [0, 1, 2, 3, 4, 5] ``` instead of ``` [0; 1; 2; 3; 4; 5] ``` From looking on the web, the comma-separated output appears to be a list converted to a string. So, my question is what does `[0, 1, 2, 3, 4, 5]` represent, and what is actually taking place, when converting from the list separated by semicolons to separated by commas? Epilogue: Fyodor Soikin's comment was correct; I was confused. It turns out, the comma-separated list was a contrivance to print out a semicolon-separated list as a comma-separated list inside array brackets. The following solution came from ehotinger on github: ``` open System [<EntryPoint>] let main argv = let s = Console.ReadLine() |> int seq { for i in 1..s do yield i } |> Seq.fold (fun s i -> if s = "" then sprintf "%i" i else sprintf "%s, %i" s i) "" |> (fun s -> sprintf "[%s]" s) |> Console.WriteLine 0 // return an integer exit code ``` I thought the list had been converted. Well it had been converted into a string containing square brackets and a comma-separated list of numbers inside the brackets.

Original source