last modified January 9, 2023
In this article, we show how to work with a List collection in F#.
A list is an ordered, immutable series of elements of the same type.
let vals = [ 1; 2; 3; 4; 5 ]
A list can be created using a list literal. A list literal consistsof elements separated with semicolons inside a pair of square brackets.
let vals = [ 1 2 3 4 5]
In an alternative syntax, the semicolons are optional.
F# List simple example
The following is a simple list example.
main.fsx
let vals = [ 1; 2; 3; 4; 5; 6 ]printfn "%A" valsprintfn "%d" vals.Headprintfn "%d" vals.Lengthprintfn "%A" vals.Tail
We have a list of integers. We print the contents of the list, its head, size,and tail.
let vals = [ 1; 2; 3; 4; 5; 6 ]
We define a list of integers with an array literal.
printfn "%A" vals
With the %A
format specifier, we pretty-print the list.
printfn "%d" vals.Head
With the Head
property, we print the first element of the list.
printfn "%d" vals.Length
We get the size of a list with Length
.
printfn "%A" vals.Tail
With Tail
, we get all but first elements of the list.
λ dotnet fsi main.fsx[1; 2; 3; 4; 5; 6]16[2; 3; 4; 5; 6]
F# List iteration
In the next example, we loop over the elements of a list.
main.fsx
let vals = [ 1; 2; 3; 4; 5; 6 ]vals |> List.iter (printfn "%d")printfn "------------------------"for e in vals do printfn "%d" e
We provide two basic ways of iteration.
vals |> List.iter (printfn "%d")
The List.iter
is the functional way of looping over list elements.
for e in vals do printfn "%d" e
The classic, imperative way is via a for loop.
λ dotnet fsi main.fsx123456------------------------123456
F# List indexes
List elements are accessed through their indexes.
main.fsx
let words = ["pen"; "cup"; "dog"; "person"; "cement"; "coal"; "spectacles"; "cup"; "bread"]let w1 = List.item 1 wordsprintfn "%s" w1let w2 = words[0]printfn "%s" w2let i1 = List.findIndex(fun e -> e = "cup") wordsprintfn $"The first index of cup is {i1}"let i2 = List.findIndexBack(fun e -> e = "cup") wordsprintfn $"The last index of cup is {i2}"
The program contains List indexing operations.
let w1 = List.item 1 words
We get the second item of the list with List.item
.
let w2 = words[0]
We can also use the classic C style syntax.
let i1 = List.findIndex(fun e -> e = "cup") words
Fith List.findIndex
, we find the first element that satisfies thegiven predicate function.
let i2 = List.findIndexBack(fun e -> e = "cup") words
Fith List.findIndexBack
, we find the last element that satisfiesthe given predicate function.
λ dotnet fsi main.fsxcuppenThe first index of cup is 1The last index of cup is 7
F# List.map
The List.map
function applies the given function to each of theelements of the collection.
main.fsx
let vals = [1..10]let res = List.map(fun e -> e * 2) valsprintfn "%A" res
We apply a map function on a list of integers.
let vals = [ 1 .. 10]
We define a list with a range operator.
let res = List.map(fun e -> e * 2) vals
Each of the elements of the list is multiplied by 2. The result is assignedto the res
variable.
λ dotnet fsi main.fsx[2; 4; 6; 8; 10; 12; 14; 16; 18; 20]
F# List.filter
We can filter list elements with List.filter
.
main.fsx
let vals = [-3; -2; 0; 1; -5; 7; 9]let words = ["sky"; "war"; "rock"; "ocean"; "cloud"; "water"]let pos = List.filter(fun e -> e > 0) valsprintfn "%A" poslet res = List.filter(fun (e:string) -> e.StartsWith("w")) wordsprintfn "%A" res
In the program, we find out all positive numbers from a list of integers andall strings which start with 'w' in a list of words.
let pos = List.filter(fun e -> e > 0) vals
The List.filter
function takes a predicate function. All elementsmust satisfy the given predicate.
let res = List.filter(fun (e:string) -> e.StartsWith("w")) words
Sometines, it is necessary to help the compiler with an explicity typedefinition.
λ dotnet fsi main.fsx[1; 7; 9]["war"; "water"]
F# merging lists
With the @
operator, we can merge two lists.
main.fsx
let a = [1; 2; 3; 4]let b = [4; 4; 5; 6]let merged = a @ b |> List.distinctprintfn "%A" mergedlet merged2 = a @ bprintfn "%A" merged2
The program merges two lists.
let merged = a @ b |> List.distinct
We merge two lists and pass the values to List.distinct
, whichremoves duplicates.
let merged2 = a @ b
We merge two lists; we have all values, including duplicates.
λ dotnet fsi main.fsx[1; 2; 3; 4; 5; 6][1; 2; 3; 4; 4; 4; 5; 6]
F# sort List of integers
In the next example, we sort integers.
main.fsx
let nums = [ -1; 6; -2; 3; 0; -4; 5; 1; 2 ]nums |> List.sort |> printfn "%A"nums |> List.sortDescending |> printfn "%A"nums |> List.sortBy (abs) |> printfn "%A"nums |> List.sortByDescending (abs) |> printfn "%A"
We have a list of integers. We sort them with List.sort
andList.sortDescending
.
nums |> List.sortBy (abs) |> printfn "%A"nums |> List.sortByDescending (abs) |> printfn "%A"
With the help of the abs
, we sort integers regarless of their sign.
λ dotnet fsi main.fsx[-4; -2; -1; 0; 1; 2; 3; 5; 6][6; 5; 3; 2; 1; 0; -1; -2; -4][0; -1; 1; -2; 2; 3; -4; 5; 6][6; 5; -4; 3; -2; 2; -1; 1; 0]
F# sort List of records
In the next example, we sort a list of records.
main.fsx
type User = { Name: string Occupation: string Salary: int }let users = [ { Name = "John Doe" Occupation = "gardener" Salary = 1280 } { Name = "Roger Roe" Occupation = "driver" Salary = 860 } { Name = "Tom Brown" Occupation = "shopkeeper" Salary = 990 } ]users|> List.sortBy (fun u -> u.Salary)|> List.iter (fun u -> printfn "%A" u)printfn "--------------------------------"users|> List.sortByDescending (fun u -> u.Occupation)|> List.iter (fun u -> printfn "%A" u)
The program contains a list of User
records. We sort the usersby their salaries and occupation.
users|> List.sortBy (fun u -> u.Salary)|> List.iter (fun u -> printfn "%A" u)
The users are sorted by salaries in ascending order withList.sortBy
.
users|> List.sortByDescending (fun u -> u.Occupation)|> List.iter (fun u -> printfn "%A" u)
Here, the users are sorted by their occupation in descending order withsortByDescending
.
λ dotnet fsi main.fsx{ Name = "Roger Roe" Occupation = "driver" Salary = 860 }{ Name = "Tom Brown" Occupation = "shopkeeper" Salary = 990 }{ Name = "John Doe" Occupation = "gardener" Salary = 1280 }--------------------------------{ Name = "Tom Brown" Occupation = "shopkeeper" Salary = 990 }{ Name = "John Doe" Occupation = "gardener" Salary = 1280 }{ Name = "Roger Roe" Occupation = "driver" Salary = 860 }
F# List comprehension
List comprehension is a powerful syntax to generate lists. List comprehensionsprovide a concise way to create lists.
In F#, we can create list comprehensions with ranges and generators.
main.fsx
let vals = [ -1; 0; 2; -2; 1; 3; 4; -6 ]let pos = [ for e in vals do if e > 0 then yield e ]printfn "%A" posprintfn "---------------------------------"[ for e in 1 .. 100 -> e * e ] |> printfn "%A"printfn "---------------------------------"[ for a in 1 .. 100 do if a % 3 = 0 && a % 5 = 0 then yield a] |> printfn "%A"printfn "---------------------------------"let vals3 = [ for x in 1 .. 3 do for y in 1 .. 10 -> x, y ]printfn "%A" vals3
In F#, list comprehensions use for loops, if conditions and the yield keyword.
let vals = [ -1; 0; 2; -2; 1; 3; 4; -6 ]let pos = [ for e in vals do if e > 0 then yield e ]
We have a list of values. A new list is constructed with a list comprehension.It contains only positive values.
[ for e in 1 .. 100 -> e * e ] |> printfn "%A"
We can use ranges in list comprehensions.
[ for a in 1 .. 100 do if a % 3 = 0 && a % 5 = 0 then yield a] |> printfn "%A"
Here we use two if conditions.
let vals3 = [ for x in 1 .. 3 do for y in 1 .. 10 -> x, y ]
Also, it is possible to use two for loops.
λ dotnet fsi main.fsx[2; 1; 3; 4]---------------------------------[1; 4; 9; 16; 25; 36; 49; 64; 81; 100; 121; 144; 169; 196; 225; 256; 289; 324; 361; 400; 441; 484; 529; 576; 625; 676; 729; 784; 841; 900; 961; 1024; 1089; 1156; 1225; 1296; 1369; 1444; 1521; 1600; 1681; 1764; 1849; 1936; 2025; 2116; 2209; 2304; 2401; 2500; 2601; 2704; 2809; 2916; 3025; 3136; 3249; 3364; 3481; 3600; 3721; 3844; 3969; 4096; 4225; 4356; 4489; 4624; 4761; 4900; 5041; 5184; 5329; 5476; 5625; 5776; 5929; 6084; 6241; 6400; 6561; 6724; 6889; 7056; 7225; 7396; 7569; 7744; 7921; 8100; 8281; 8464; 8649; 8836; 9025; 9216; 9409; 9604; 9801; 10000]---------------------------------[15; 30; 45; 60; 75; 90]---------------------------------[(1, 1); (1, 2); (1, 3); (1, 4); (1, 5); (1, 6); (1, 7); (1, 8); (1, 9); (1, 10); (2, 1); (2, 2); (2, 3); (2, 4); (2, 5); (2, 6); (2, 7); (2, 8); (2, 9); (2, 10); (3, 1); (3, 2); (3, 3); (3, 4); (3, 5); (3, 6); (3, 7); (3, 8); (3, 9); (3, 10)]
In this article we have worked with lists in F#.
FAQs
Why is F# not popular? ›
This attitude towards the language by its very progenitor is one reason why F# has not yet become highly recognised for its suitability, beyond just data science, for both front end and back end development, while the barrier to its adoption continues to be cyclical: there are few jobs advertising for F# developers ...
How to concatenate two lists in F#? ›You can concatenate lists that have compatible types by using the @ operator, as in the following code. If list1 is [2; 3; 4] and list2 is [100; 2; 3; 4] , this code creates list3 as [2; 3; 4; 100; 2; 3; 4] .
How do I print a list in F sharp? ›You can give it a format specifier to print an entire list (using F# formatting) or print just a first few elements (which happens when you call ToString ): > printfn "%A" [ 1 .. 5 ];; // Full list using F# formatting [1; 2; 3; 4; 5] > printfn "%O" [ 1 .. 5 ];; // Using ToString (same as WriteLine) [1; 2; 3; ... ]
What is the difference between sequence and list F#? ›Sequences, commonly called sequence expressions, are similar to lists: both data structures are used to represent an ordered collection of values. However, unlike lists, elements in a sequence are computed as they are needed (or "lazily"), rather than computed all at once.
Is F# faster than C#? ›Task Runtime Performance
Asynchronous code (Tasks) in C# runs faster than in F# because the compiler supports them natively and generates optimized code. The difference may be reduced, once F# supports tasks natively, too.
This kind of approach is shown throughout the language, meaning that you'll have much more confidence when your code compiles that it actually works as you expect it to, than not. Although F# is different from the majority of popular mainstream languages out there, it's not hard to learn.
How do I combine nested lists into one list? ›Use the sum() function to concatenate nested lists to a single list by passing an empty list as a second argument to it.
How do you intersect two lists? ›- # Python program to get the intersection.
- # of two lists in most simple way.
- def intersection_list(list1, list2):
- list3 = [value for value in list1 if value in list2]
- return list3.
- # Driver Code.
- list1 = [40, 90, 11, 58, 31, 66, 28, 54, 79]
- list2 = [58, 90, 54, 31, 45, 11, 66, 28, 26]
Concatenation operator (+) for List Concatenation. The '+' operator can be used to concatenate two lists. It appends one list at the end of the other list and results in a new list as output.
How do I print a list of items in a string? ›- str() function; that will convert the given data type into the string data type.
- An iterable sequence; each and every element in the sequence will be called by str() function. The string values will be returned through an iterator.
How do I print a sublist list? ›
Step 1 : given a list. Step 2 : take one sublist which is empty initially. Step 3 : use one for loop till length of the given list. Step 4 : Run a loop from i+1 to length of the list to get all the sub arrays from i to its right.
Is list better than array? ›An array is faster than a list in python since all the elements stored in an array are homogeneous i.e., they have the same data type whereas a list contains heterogeneous elements. Moreover, Python arrays are implemented in C which makes it a lot faster than lists that are built-in in Python itself.
What does the list () function do? ›The list() function creates a list object. A list object is a collection which is ordered and changeable.
Why is F# so slow? ›From my experience generally speaking a program in idiomatic F# allocates more garbage and is harder to optimize by the JIT compiler than a similar program in idiomatic C#. The runtime and standard library are in practise mostly designed and optimized for C#, so fewer engineering hours are spent on making F# fast.
Is F# good for data science? ›F# is an excellent solution for programmatic data science as it combines efficient execution, REPL-scripting, powerful libraries and scalable data integration.
What is F# best for? ›F# is a universal programming language for writing succinct, robust and performant code. F# allows you to write uncluttered, self-documenting code, where your focus remains on your problem domain, rather than the details of programming.
Is F# still used? ›Plug-ins supporting F# exist for many widely used editors including Visual Studio Code, Vim, and Emacs. F# is a member of the ML language family and originated as a . NET Framework implementation of a core of the programming language OCaml. It has also been influenced by C#, Python, Haskell, Scala and Erlang.
How long does it take to learn F#? ›All in all I would say it took me a week to learn the syntax and basics of the language in my spare time (2-3 hours a night). You'll need more time than that to get a real feel for functional programming though.
Will F# replace C#? ›Don Syme in his SPLASH talk says that F# is NOT intended to be a replacement for C# even though it has the general capabilities. He goes on to say that there are areas where F# makes no sense in using, but doesn't expand on the thesis.
How do you flatten a list of lists with a list comprehensions? ›To flatten a list of lists, use the list comprehension statement [x for l in lst for x in l] . To modify all elements in a list of lists (e.g., increment them by one), use a list comprehension of list comprehensions [[x+1 for x in l] for l in lst] .
How do I combine two lists without duplicates? ›
In Excel, you can merge two lists without duplicating any value by using the Remove Duplicates feature.
Can lists be nested within each other? ›A nested list is a list inside another list. You can create a nested unordered list, or a nested ordered list, or even an ordered list nested inside an unordered one.
What is intersection of two linked lists? ›The key idea to note is that, if the two linked lists contain a common point, the length from that intersection point to the tail will be the same. Since the tail length must be the same, the intersection node should be any of the first five nodes in the given image.
Can you use split () on a list? ›A split function can be used to split strings with the help of a delimiter. A split function can be used to split strings with the help of the occurrence of a character. A split function can be used to split strings in the form of a list.
How do I merge and sort two lists? ›- Define the two variables to assign the empty lists.
- Now takes the number of inputs for the first and second list.
- Now merge both lists using the '+' operator.
- Use the built-in sort() method to sort the newly created list.
append() adds a list inside of a list. Lists are objects, and when you use . append() to add another list into a list, the new items will be added as a single object (item).
What is the most efficient way to concatenate lists? ›The extend() method is also the most concise and fastest way to concatenate lists compared to all other methods. Here is an example of how we can use the extend() method to join two lists, list_one and list_two together.
Can only concatenate list to list? ›The “TypeError: can only concatenate list (not “int”) to list” error is raised when you try to concatenate an integer to a list. This error is raised because only lists can be concatenated to lists. To solve this error, use the append() method to add an item to a list.
Are the unions of F# discriminated? ›In this case the new type is the “sum” of the integer type plus the boolean type. In F#, a sum type is called a “discriminated union” type. Each component type (called a union case) must be tagged with a label (called a case identifier or tag) so that they can be told apart (“discriminated”).
Is GB or F# more common? ›F# is much more common than Gb, so we'll approach most of the chords below from the F# perspective. Each of these notes (degrees of the scale) can be assigned a number as it ascends so you can use a helpful formula to work out chords from it.
Why is C# better than F#? ›
The C# code has lots of “noise”, things like curly braces, semicolons, etc. And in C# the functions cannot stand alone, but need to be added to some class (“SumOfSquaresHelper”). F# uses whitespace instead of parentheses, needs no line terminator, and the functions can stand alone.
Why do big companies hate unions? ›The most common reason companies say they oppose labor unions is because they want to have a direct relationship with their employees. It also costs them more money. Research shows that the growth of union jobs correlates to higher wages for the lowest-paid workers.
Why do big companies fear unions? ›Large firms often oppose unions due to their impact on the company's autonomy and fears of economic losses as workers fight for higher wages and better benefits.
Why are managers against unions? ›Managers are also against union representation because it limits flexibility, unions promote strikes which can be nightmares for managers; managers cannot decide on workplace policies without consulting the union, and grievance procedures are tedious for managers.
Is F# good for machine learning? ›F# excels at data science and machine learning. This article gives links to some significant resources related to this mode of use of F#. For information about other options that are available for machine learning and data science, see the F# Software Foundation's Guide to Data Science with F#.
Is F# a good functional language? ›F# makes it easy to write concise code to solve complex problems on all the major desktop and mobile platforms, primarily using functional programming. F# is a strongly typed, functional-first programming language that lets you solve complex problems by writing simple code.
Is F# static or dynamic? ›F# is a statically typed language, which means that the compiler deduces an exact type for each construct during compilation.
Is F# A major key? ›F-sharp major (or the key of F♯) is a major scale based on F♯, consisting of the pitches F♯, G♯, A♯, B, C♯, D♯, and E♯.
What language is replacing C#? ›Java, Python, JavaScript, Golang, and PHP are the most popular alternatives and competitors to C#.
Is C sharp harder than Python? ›While Python is easier to learn and write than C# and has vast standard libraries. Both C# and Python are excellent programming languages. Thus, picking one over the other is more a matter of preference than the risk of choosing the wrong language for the project.