Range Over Built in F#

Here is the translated code and explanation in F#:

range iterates over elements in a variety of built-in data structures. Let’s see how to use range with some of the data structures we’ve already learned.

Here we use range to sum the numbers in a list. Arrays work like this too.

open System

[<EntryPoint>]
let main argv =
    let nums = [2; 3; 4]
    let mutable sum = 0
    for num in nums do
        sum <- sum + num
    printfn "sum: %d" sum

    // `range` on arrays and lists provides both the
    // index and value for each entry. Above we didn’t
    // need the index, so we ignored it. Sometimes we actually want
    // the indexes though.
    for i in 0 .. nums.Length - 1 do
        let num = nums.[i]
        if num = 3 then
            printfn "index: %d" i

    // `range` on map (Dictionary) iterates over key/value pairs.
    let kvs = dict ["a", "apple"; "b", "banana"]
    for kvp in kvs do
        let key = kvp.Key
        let value = kvp.Value
        printfn "%s -> %s" key value

    // `range` can also iterate over just the keys of a map.
    for key in kvs.Keys do
        printfn "key: %s" key

    // `range` on strings iterates over Unicode code points.
    // The first value is the starting byte index
    // of the `char` and the second the `char` itself.
    let str = "go"
    let chars = str.ToCharArray()

    for i in 0 .. chars.Length - 1 do
        let c = chars.[i]
        printfn "%d %d" i (int c)

    0

To run the program, save the code in a .fs file (e.g., RangeOverBuiltInTypes.fsx) and use dotnet run or fsharpi if you are using the F# Interactive.

$ dotnet fsi RangeOverBuiltInTypes.fsx
sum: 9
index: 1
a -> apple
b -> banana
key: a
key: b
0 103
1 111

Or if you prefer to compile and run:

$ dotnet build -o out
$ dotnet out/RangeOverBuiltInTypes.dll
sum: 9
index: 1
a -> apple
b -> banana
key: a
key: b
0 103
1 111

Now that we can run and build basic F# programs, let’s learn more about the language.