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 OO 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 ...

Get Programming Elixir 1.3 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.