Common functions
Functions available in multiple modules, each version customized for its target type
Operations: access, construct, find, select, aggregate...
โ๏ธ Convention used here:
Functions are given by their name
To use them, we need to qualify them by the module.
The last parameter is omitted for brevity
It's always the collection.
Example: head vs List.head x
Access to an element
By index
x[index]
By index
item index
tryItem index
First element
head
tryHead
Last element
last
tryLast
๐ฃ ArgumentException or IndexOutOfRangeException
[1; 2] |> List.tryHead // Some 1
[1; 2] |> List.tryItem 2 // NoneCost โ ๏ธ
head
O(1)
O(1)
O(1)
item
O(1)
O(n) โ
O(n) โ
last
O(1)
O(n) โ
O(n) โ
length
O(1)
O(n) โ
O(n) โ
Combine collections
append / @
2 collections of sizes N1 et N2
N1 + N2
concat
K collections of sizes N1..Nk
N1 + N2 + ... + Nk
zip
2 collections of same size N โ
N pairs
allPairs
2 collections of sizes N1 et N2
N1 * N2 pairs
Find an element
Using a predicate f : 'T -> bool:
First found
find
tryFind
Last found
findBack
tryFindBack
Index of first found
findIndex
tryFindIndex
Index of last found
findIndexBack
tryFindIndexBack
Search elements
By value
At least 1
contains value
By predicate f
At least 1
exists f
"
All
forall f
Select elements
All those found
filter f
First ignored
skip n
skipWhile f
First found
take n
takeWhile f
truncate n
โ Notes:
skip,takevstruncatewhenn> collection's sizeskip,take: ๐ฃ exceptiontruncate: empty collections w/o exception
Alternative for
Array: Rangearr[2..5]
Map elements
Functions taking as input:
A mapping function
f(a.k.a. mapper)A collection of type
~~~~ 'Twith~~~~meaningArray,List, orSeq
map
ย ย ย ย ย ย ย 'T -> 'Uย ย ย ย ย ย
'U ~~~~
As many in than out
mapi
int -> 'T -> 'Uย ย ย ย ย ย
'U ~~~~
As many in than out
collect
ย ย ย ย ย ย ย 'T -> 'U ~~~~ย
'U ~~~~
flatMap
choose
ย ย ย ย ย ย ย 'T -> 'U option
'U ~~~~
Less
pick
ย ย ย ย ย ย ย 'T -> 'U option
'Uย ย ย ย ย
1 (the first matching) or ๐ฃ
tryPick
ย ย ย ย ย ย ย 'T -> 'U option
'U option
1 (the first matching)
map vs mapi
map vs mapimapi โก map with index
The difference is on the f mapping parameter:
map:'T -> 'Umapi:int -> 'T -> 'Uโ the additionalintparameter is the item index
Alternative to mapi
mapiApart from map and iter, no xxx function has a xxxi variant.
๐ก Use indexed to obtain elements with their index
map vs iter
map vs iteriter looks like map with
no mapping:
'T -> unitvs'T -> 'Uno output:
unitvs'U list
But iter is used for a different use case:
โ to trigger an action, a side-effect, for each item
Example: print the item to the console
choose, pick, tryPick
choose, pick, tryPickSignatures:
โข choose : mapper: ('T -> 'U option) -> items: 'T ~~~~ -> 'U ~~~~
โข pick : mapper: ('T -> 'U option) -> items: 'T ~~~~ -> 'U
โข tryPick : mapper: ('T -> 'U option) -> items: 'T ~~~~ -> 'U option
Notes:
The mapper may return
Nonefor some items not mappable (or just ignored)~~~~stands for the collection type:Array,List, orSeq
Different use cases:
chooseto get all the mappable items mappedpickortryPickto get the first one
When no items are mappable:
choosereturns an empty collectiontryPickreturnsNonepickraises aKeyNotFoundException๐ฃ
Examples:
Analogies:
choose f โ
โข collect (f >> Option.to{Collection})
โข (filter (f >> Option.isSome)) >> (map (f >> Option.value))
(try)pick f โ
โข (try)find(f >> Option.isSome)) >> f
โข choose f >> (try)head
Aggregate
Specialized aggregate functions
ร
countBy
ร
max
maxBy
comparison
min
minBy
comparison
sum
sumBy
Monoid๐
average
averageBy
Monoid๐
CountBy
Uses a projection f: 'T -> 'U to compute a "key" for each item
Returns all the keys with the number of items having this key
๐ก Useful to determine duplicates:
Max(By), Min(By)
โ๏ธ Notes:
Unions are
IComparableby default โNfollows thecomparisonconstraint.maxByandminByperform no mapping: โ See the returned value in the example:Two(N), โ"Two"(string)
Sum(By), Average(By)
โ๏ธ Notes:
The error
FS0001at line 1 reveals the Monoid constraint (see below) that must be satisfied by:The item type
'Tforsumandaverage,The projection return type
'UforsumByandaverageBy.
sumByandaverageByperform a mapping โ See the returned type in the example:intโ item type:int * stringsumโกsumBy idaverageโกaverageBy id
Monoid constraint
To satisfy the monoid constraint, a type must have:
A
Zerostatic read-only propertyAn overload of the
+operator
Example of a custom type with these members:
Versatile aggregate functions
โข fold (f: 'U -> 'T -> 'U) (seed: 'U) items
โข foldBack (f: 'T -> 'U -> 'U) items (seed: 'U)
โข reduce (f: 'T -> 'T -> 'T) items
โข reduceBack (f: 'T -> 'T -> 'T) items
f takes 2 parameters: an "accumulator" acc and the current element x
โ For foldBack, the parameters are in a reversed order: x acc
xxxBack vs xxx:
Iterates from last to first element
Parameters
seedanditemsreversed (forfoldBack)
reduce(Back) vs fold(Back):
reduce(Back)uses the first item as the seed and performs no mapping (see'T -> 'Tvs'T -> 'U)reduce(Back)fails if the collection is empty ๐ฃ
Examples:
Fold(Back) versatility
We could write almost all functions with fold or foldBack (performance aside)
Change the order of elements
Inversion
rev list
ร
Sort asc
sort list
sortBy f list
Sort desc
sortDescending list
sortDescendingBy f list
Sort custom
sortWith comparer list
ร
Separate
๐ก Elements are divided into groups
[1..10]
[ 1 2 3 4 5 6 7 8 9 10 ]
length = 10
chunkBySize 3
[[1 2 3] [4 5 6] [7 8 9] [10]]
forall: length <= 3
splitInto 3
[[1 2 3 4] [5 6 7] [8 9 10]]
length <= 3
splitAt 3
([1 2 3],[4 5 6 7 8 9 10])
Tuple โ
โ๏ธ Notice how splitInto n distributes the items equally, from left to right:
Group items
By size
๐ก Items can be duplicated into different groups
[1..5]
[ 1 2 3 4 5 ]
pairwise
[(1,2) (2,3) (3,4) (4,5)]
Tuple โ
windowed 2
[[1 2] [2 3] [3 4] [4 5]]
Array of arrays of 2 items
windowed 3
[[1 2 3] [2 3 4] [3 4 5]]
Array of arrays of 3 items
By criteria
partition
predicate: 'T -> bool
('T list * 'T list)
โ 1 pair ([OKs], [KOs])
groupBy
projection: 'T -> 'K
('K * 'T list) list
โ N tuples [(key, [related items])]
Change collection type
Your choice: Dest.ofSource or Source.toDest
From \ to
Array
List
Seq
Array
ร
List.ofArray
Seq.ofArray
ร
Array.toList
Array.toSeq
List
Array.ofList
ร
Seq.ofList
List.toArray
ร
List.toSeq
Seq
Array.ofSeq
List.ofSeq
ร
Seq.toArray
Seq.toList
ร
Functions vs comprehension
The functions of List/Array/Seq can often be replaced by a comprehension, more versatile:
Additional resources
Documentation FSharp.Core ๐
Last updated
Was this helpful?