F# Guide — Collections: Set, Map, and Advanced Operations
In this tutorial, you will learn about F# Guide. We cover key concepts, practical examples, and best practices to help you master this topic.
F# collections include immutable Sets for unique elements and Maps for key-value associations, plus advanced operations on lists, arrays, and sequences for complex data transformations.
What You'll Learn
- Sets: creation and operations
- Maps: key-value dictionaries
- Collection conversion
- Advanced list/array operations
- Choosing the right collection
Why It Matters
Choosing the right collection type and using advanced operations leads to cleaner, faster code. Durga Antivirus Pro uses Sets for unique threat signatures and Maps for configuration.
Real-World Use
Sets for unique item tracking, Maps for lookup tables, advanced operations for data analysis and Etl Pipelines.
flowchart LR
A["Collections"] --> B["Sets"]
B --> C["Maps"]
C --> D["Advanced Ops"]
D --> E["Selection"]
A:::current --> B
style A fill:#2563eb,stroke:#2563eb,color:#fff
style B fill:#dbeafe,stroke:#2563eb,color:#1e40af
style C fill:#dbeafe,stroke:#2563eb,color:#1e40af
style D fill:#dbeafe,stroke:#2563eb,color:#1e40af
style E fill:#f1f5f9,stroke:#94a3b8,color:#64748b
Sets
// Create sets
let set1 = Set.ofList [1; 2; 3; 2; 1] // set [1; 2; 3]
let set2 = Set.ofArray [|3; 4; 5|] // set [3; 4; 5]
// Set literal
let letters = set ['a'; 'b'; 'c']
// Set operations
Set.union set1 set2 // set [1; 2; 3; 4; 5]
Set.intersect set1 set2 // set [3]
Set.difference set1 set2 // set [1; 2]
Set.isSubset set1 set2 // false
// Membership
set1 |> Set.contains 2 // true
set1 |> Set.add 5 // set [1; 2; 3; 5]
set1 |> Set.remove 2 // set [1; 3]
Maps
// Create maps
let map1 = Map.ofList [("a", 1); ("b", 2); ("c", 3)]
// Map literal
let config = Map ["host", "localhost"; "port", "8080"]
// Access
map1.["a"] // 1
map1 |> Map.tryFind "a" // Some 1
map1 |> Map.tryFind "z" // None
// Operations
map1 |> Map.add "d" 4
map1 |> Map.remove "a"
map1 |> Map.containsKey "b" // true
map1 |> Map.map (fun k v -> v * 2)
Advanced List Operations
let list = [1; 2; 3; 4; 5; 6]
// Partition into two lists
let evens, odds = list |> List.partition (fun x -> x % 2 = 0)
// Split at index
let first, rest = list |> List.splitAt 3
// Windows and chunks
list |> List.windowed 3 // [[1;2;3]; [2;3;4]; [3;4;5]; [4;5;6]]
list |> List.chunkBySize 2 // [[1;2]; [3;4]; [5;6]]
// Distinct
[1; 1; 2; 3; 2] |> List.distinct // [1; 2; 3]
[1; 1; 2; 3; 2] |> List.countBy id // [(1, 2); (2, 2); (3, 1)]
Advanced Array Operations
let arr = [|1; 5; 2; 8; 3|]
// Sorting
arr |> Array.sort // [|1; 2; 3; 5; 8|]
arr |> Array.sortByDescending (fun x -> x) // [|8; 5; 3; 2; 1|]
// Search
arr |> Array.tryFind (fun x -> x > 5) // Some 8
arr |> Array.findIndex (fun x -> x = 2) // 2
arr |> Array.contains 8 // true
// Sub-arrays
arr |> Array.skip 2 // [|2; 8; 3|]
arr |> Array.take 2 // [|1; 5|]
Collection Conversion
// Between collections
List.ofArray [|1; 2; 3|]
Array.ofList [1; 2; 3]
Set.ofList [1; 2; 3]
Map.ofList [("a", 1); ("b", 2)]
// To sequences
List.toSeq [1; 2; 3]
Array.toSeq [|1; 2; 3|]
// From sequences
Seq.toList (seq {1..3})
Seq.toArray (seq {1..3})
Choosing Collections
// Guidelines:
// List: functional transformations, small-medium data
// Array: fast indexing, mutable, numerical
// Seq: lazy, large data, I/O streaming
// Set: unique elements, membership tests
// Map: key-value lookup, configuration
Common Mistakes
1. Using lists for random access
Lists are O(n) for indexing. Use arrays for indexed access.
2. Forgetting Set uniqueness
Adding duplicates to a Set does nothing. No error. The duplicate is simply not added.
3. Map key not found
Using map.[key] on a missing key throws. Use Map.tryFind for safe access.
4. Unnecessary conversions
Converting between collection types has cost. Start with the right collection.
5. Ignoring performance for large collections
For large data, prefer arrays or sequences. Lists have higher overhead.
Practice Questions
1. What is the difference between Set and Map? A Set stores unique values. A Map stores key-value pairs with unique keys.
2. How do you safely access a Map value?
Use Map.tryFind key map which returns 'T option instead of throwing.
3. When would you use Seq over List? For lazy evaluation, large datasets, file I/O streaming, and potentially infinite sequences.
Challenge: Write a function that finds duplicate elements in a list using Set operations.
FAQ
{{< faq question="Are Set and Map faster than List?" >}} Sets and Maps have O(log n) lookup vs O(n) for lists. For large collections and frequent lookups, Sets and Maps are faster. {{< /faq >}}
{{< faq question="Can I have mutable sets and maps?" >}}
Yes, use System.Collections.Generic.HashSet<'T> or Dictionary<'TKey, 'TValue> for mutable variants.
{{< /faq >}}
{{< faq question="What is Map.ofList?" >}} Creates a Map from a list of key-value tuples. If duplicate keys exist, the last one wins. {{< /faq >}}
{{< faq question="Can collections be nested?" >}}
Yes: Map<string, Set<int>>, Set<Set<int>>, etc. All combinations work.
{{< /faq >}}
{{< faq question="How do I iterate over a Map?" >}}
Maps implement IEnumerable of KeyValuePair. Use for (KeyValue(k, v)) in map do or Map.iter.
{{< /faq >}}
Mini Project
Build an inventory management system using Maps:
type Inventory = Map<string, int>
let addItem (inv: Inventory) item quantity =
match inv |> Map.tryFind item with
| Some q -> inv |> Map.add item (q + quantity)
| None -> inv |> Map.add item quantity
let removeItem (inv: Inventory) item quantity =
match inv |> Map.tryFind item with
| Some q when q > quantity -> inv |> Map.add item (q - quantity)
| Some q when q = quantity -> inv |> Map.remove item
| _ -> Error "Insufficient stock"
let checkStock inv item =
inv |> Map.tryFind item |> Option.defaultValue 0
What's Next
Now that you understand collections, explore pipelines and data flow programming.
| Topic | Description | Link |
|---|---|---|
| F# Pipelines | Data processing pipelines | {{< ref "16-pipelines" >}} |
| F# Composition | Function composition | {{< ref "17-composition" >}} |
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro