Range Over Iterators in F#

Our example will demonstrate how to work with iterators and linked lists. Here’s the full source code.

open System

// Define an element and list type
type Element<'T> = 
    { mutable Next: Element<'T> option
      Value: 'T }

type List<'T>() =
    let mutable head: Element<'T> option = None
    let mutable tail: Element<'T> option = None
    
    member this.Push (value: 'T) =
        let newElement = { Next = None; Value = value }
        match tail with
        | None ->
            head <- Some newElement
            tail <- Some newElement
        | Some lastElement ->
            lastElement.Next <- Some newElement
            tail <- Some newElement
    
    member this.All () = seq {
        let mutable current = head
        while current.IsSome do
            yield current.Value.Value
            current <- current.Value.Next
    }

// Generator function for Fibonacci sequence
let genFib () = seq {
    let mutable a = 1
    let mutable b = 1
    while true do
        yield a
        let temp = a
        a <- b
        b <- temp + b
}

[<EntryPoint>]
let main argv =
    // Create and populate the list
    let lst = List<int>()
    lst.Push 10
    lst.Push 13
    lst.Push 23

    // Iterate over the list and print elements
    for e in lst.All() do
        printfn "%d" e

    // Collect all elements into a list
    let all = lst.All() |> Seq.toList
    printfn "all: %A" all
    
    // Generate Fibonacci numbers
    for n in genFib() do
        if n >= 10 then
            break
        printfn "%d" n

    0

Let’s break down what this example does:

  • We define a generic Element and List type. Each element can be linked to the next element creating a linked list.
  • The Push method adds values to the list.
  • The All method returns an F# sequence (seq) that iterates over all elements.
  • genFib generates an infinite sequence of Fibonacci numbers.
  • In the main function, we create a list, populate it, and print the items.
  • We also use the genFib function to print Fibonacci numbers until a specific condition is met.

Running this code will produce the following output:

10
13
23
all: [10; 13; 23]
1
1
2
3
5
8

Next example: Errors.