SECRET OF CSS

How To Use Control Structures in Elixir | by Eduardo Lalangas Rico Sotomayor | Aug, 2022


How to use case, cond, if, and unless in Elixir

1*bobWISMquSll2o0g9a3Imw
Taken from https://elixir-lang.org/

In the past entries, we saw the data types in Elixir and pattern matching. Now, we will see functions that will allow us to control the flow of our applications. Surely, you are already familiar with some like if-else and case.

It is used to match a result with several possible values. The idea is similar to pattern matching. We want to match an object, and depending on whether it matches or not, we do something, and we can get values from the same case. Let’s see the syntax below:

Remember that the pin operator ^ is used to match an existing value with a pattern. Let’s see an example with this operator:

Each case clause allows us to specify special conditions using guards, for example, to ensure that a value exists in an interval. Let’s see an example below:

It is important to mention that errors in guards do not propagate; they just makes the clause fail. For example, in this next case hd(1) fails because the hd function needs a non-empty list as an argument. If it does not fail, it just passes to the next clause.

If we have a structure with a single clause that does not match, we will have an exception.

This control structure is used to match a result with different conditions until it evaluates to one that is neither :nil nor :false, there must always be a default condition that evaluates to true.

The syntax is very similar to case, as you can see below:

If there is no condition returning true, there will be an exception. Here’s the code to show that:

It is important to consider that any value other than nil or false is considered true.

They are useful to check only one condition, just like unless it is very similar to any other if of other programming languages.

Unless is equivalent to if but expects a false value.

In this case, the code block will return a nil. Both if and unless support else.

For unless, however, its use is discouraged because it is less legible.

If any variable is declared or changed in a block such as if/unless, cond, or case, the declaration and changes will only be visible in that structure.

If we want the variable to change, we have to reassign the value to the result of the block, as shown below:

Although it may seem complicated at first, I think Elixir provides very efficient tools to control the flow of applications. It’s just a matter of learning how functional programming languages work, and then you will love it!



News Credit

%d bloggers like this: