Frequently Asked Questions

cedricss edited this page Aug 24, 2012 · 5 revisions

We just started this FAQ wiki page! This page can be edited by everyone, don't hesitate to contribute!

To learn more about Opa, check out the Opa Documentation, the API and the Reference Card.

How to update a record field?

I have a record representing a user, for example:

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

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

baby.age = 21


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.

How to insert a new element in a map?

I have this initial users intmap:

users = IntMap.empty

My map is still empty after this:

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


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

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

How to modify a value in an imperative style?

I understand Opa is a functional programming language, but what if I really need to do side effects on my values, for example to write an imperative algorithm?

Use the Mutable module:

m = Mutable.make(0);
m.get(); // => 0
m.get(); // => 1