Coding with Immutable Data

Once you accept the concept, coding with immutable data is surprisingly easy. You just have to remember that any function that transforms data will return a new copy of it. Thus, we never capitalize a string. Instead, we return a capitalized copy of a string.

 iex>​ name = ​"​​elixir"
 "elixir"
 iex>​ cap_name = String.capitalize name
 "Elixir"
 iex>​ name
 "elixir"

If you’re coming from an object-oriented language, you may dislike that we write String.capitalize name and not name.capitalize(). But in object-oriented languages, objects mostly have mutable state. When you make a call such as name.capitalize() you have no immediate indication whether you are changing the internal representation of the name, returning a capitalized copy, or both. There’s plenty of scope for ambiguity.

In a functional language, we always transform data. We never modify it in place. The syntax reminds us of this every time we use it.

That’s enough theory. It’s time to start learning the language. In the next chapter we’ll quickly go over the basic data types and some syntax, and in the following chapters we’ll look at functions and modules.