F# Mutable vs Redefine

One of the first things we learn about F# is that all values are immutable. This is where much of the power of functional programming is derived. There are however a couple of ways to change the value of an identifier. Let's examine how this is done and what the differences are.

First we are able to redefine identifiers within functions by using the let keyword. This is useful when you want to have intermediate values which will not be referenced later, so there is no need to give them their own names.

Now lets look at type and scope:

Notice that when redefining a value using the let keyword, we are able change the type and value of the identifier. In the third line, valName is of type seq and is later redefined as a string. In this example, we are also able to see the scope of valName. Although it is redefined in the innerFunction, the value is unchanged when the innerFunction is complete.

Now lets look at the mutable Keyword. This keyword shows how F# can be used for imperative programming. We simply put the word mutable after let to define the identifier and then use the left arrow (<-) to change the value.

When using the mutable keyword, we are not able to change the type of the identifier, just the value. Notice the error in the next example.

Another important note about mutable identifiers is that you can not change the value of the identifier from within a subfunction. The following example demonstrates the scope error.

Hopefully this helps to clarify mutable vs immutable in F#.


Al Tenhundfeld said...

Hey Amanda,

Sorry to hear you're stuck in Richmond. I enjoyed your F# talk. I especially appreciated your comments at the end (paraphrasing): ...Functional programming is cool and will improve your OOP. But the most important thing is to learn something new! It doesn't matter if it's F# or IronRuby or whatever, as long it's something different that forces you to think in new ways.


After my current ridiculous deadline is completed, I hope to have some time to play with F#, although Spec# is pretty intriguing also.

Anyway, thanks for making the trip down to VA. I think you win the award for having highest percentage of presenters and MVPs in your presentation.