Lists in F#
Lists typically play an important role in functional programming and F# is no different. Lists are simply a typed collection of values. By "typed" I mean that the list can only contain entities of the list's type. Type the following code into the F# Interactive:
> let list = [1;2;3];;
val list : int list
The Interactive shows us that our list value has the type of int. Now lets try and create a string list and concatenate our two lists: using the @ operator:
> let list2 = ["a";"b";"c"];;
val list2 : string list
> let list3 = list @ list2;;
stdin(15,19): error: FS0001: Type mismatch
As you can see we get a type mismatch here. This is to be expected since lists are typed and that operation is trying to concatenate lists of two different types. Here's a successful concatenation with string lists:
> let list1 = ["a";"b";"c"] @ ["d";"e";"f"];;
val list1 : string list
>list1;;
val it : string list = ["a"; "b"; "c"; "d"; "e"; "f"]
Other operations on lists
| Example |
Description |
| > [];; |
Empty List |
| val it : 'a list = [] |
| > "a" :: "b" :: "c" :: [];; |
Adds an element to the head of a list. Similar to Lisp's "cons" |
| val it : int list = ["a"; "b"; "c"] |
| [1..5];; |
Declares a range of elements in a list |
| val it : int list = [1; 2; 3; 4; 5] |