Tuesday, February 3, 2009

F# - Immutability

Many F# data structures are immutable. Immutable means data can't be modified. It is one of the main ideas of functional programming. Let’s look at the following code:

#light
let text = "Hello F#"
printf "4th character: %c" text.[3]
4th character: l

Dynamic data modification can be done by using the <- operator. Let’s try to modify the 4th character of the string.

> a.[3] <- 'r';;

  a.[3] <- 'r';;
  ^^^^^^^^^^^^^

stdin(8,1): error FS0191: invalid indexer expression.

It means that a character of a string cannot be modified because a string is an immutable type. There are no background mechanism, to cover string immutability, similar to C#.

Array is also an immutable type. Here is an example:

let enumFruits fruitList =
    List.iter (fun element -> printf "[%s] " element) fruitList
    printfn ""

let fruits = ["Apple"; "Banana"; "Cherry"]
printf "Fruits: "
enumFruits fruits

"Nut"::fruits
printf "Fruits: "
enumFruits fruits

let extFruits = "Nut"::fruits
printf "extFruits: "
enumFruits extFruits
Fruits: [Apple] [Banana] [Cherry]
Fruits: [Apple] [Banana] [Cherry]
extFruits: [Nut] [Apple] [Banana] [Cherry]

enumFruits is a function to enumerate the items of the fruit list.

The fruits array initially contains 3 elements: Apple, Banana, Cherry. The :: operator attaches an element called Nut to the head of the array. Inspecting the elements of fruits reveals that nothing has changed, fruits contains the same 3 elements. Array is immutable. extFruits is just for showing that :: operator really works.

No comments:

Post a Comment