Skip to content

Frequently Asked Questions

cedricss edited this page Aug 22, 2012 · 5 revisions

Update a record

I have a record representing a user, for example:

baby = { name : "Alice", age : 1};

How to change the age of the baby?

I tried this to change the age, but it doesn't work:

baby.age = 21

Here is the solution:

adult = { baby with age : 21 }
Opa is a functional language, it means you can't do such side-effect on your values: this is something we believe makes the language safer and easier to debug.

In an imperative language, where it would be valid to do this, it means the "baby" you defined at the beginning of your code can have its age changed elsewhere in the code: the object you would manipulate in the future has suddenly nothing to do with a baby and you have no clue it has changed. With a functional language you have the guarantee a value you defined can't be affected by other external function.

Update a map

I have this initial users intmap:

users = IntMap.empty

How to add a user in this map?

My map is still empty after this:

IntMap.add(1, "Alice", users)

Solution:

users = IntMap.add(1, "Alice", users)

Understand why reading in the functional language section. Some related discussion about maps can be found here: