DEV Community

BigSpaces
BigSpaces

Posted on

Lists operations from right to left. Was this really needed?

Today my little brain got one of the concepts that I wasn't quite getting.

What is this thing about Elixir evaluating operations from right to left when it comes to lists? I can hear José Valim giggle: "this is going to break a few brains, mwahahahahaha".

Ok, José, close call, but I got this one. Gimme something trickier.

I was initially confused by this:

Image description

WHAAAAAAAAAAAT thaaa

2?

But, but, one minus one is zero and two minus two is zero, so one and two minus one and minus two...

Image description

So I went back to Apples And Oranges. Sesame-Street my life.

Here is my genius achievement of the day. One more step to Elixir Everest.

Image description

Here is looking at you, José

Image description

git add .
git commit -m "I am sure there is a reason for this madness"

BigSpaces

Top comments (3)

Collapse
 
bartoszgorka96 profile image
Bartosz Górka

@bigspaces I can resolve your issue. This operator is right associative. Let's check Elixir docs for Kernel.--/2.

List subtraction operator. Removes the first occurrence of an element on the
left list for each element on the right.

This function is optimized so the complexity of a -- b is proportional to
length(a) * log(length(b)). See also the Erlang efficiency guide
(https://erlang.org/doc/efficiency_guide/retired_myths.html).

Inlined by the compiler.

## Examples

    iex> [1, 2, 3] -- [1, 2]
    [3]

    iex> [1, 2, 3, 2, 1] -- [1, 2, 2]
    [3, 1]

The --/2 operator is right associative, meaning:

    iex> [1, 2, 3] -- [2] -- [3]
    [1, 3]

As it is equivalent to:

    iex> [1, 2, 3] -- ([2] -- [3])
    [1, 3]
Enter fullscreen mode Exit fullscreen mode

The last example is exactly as you defined in your post. Technically it will be executed as:

[1, 2] -- [1] -- [2]
=> [1, 2] -- ([1] -- [2])
=> [1, 2] -- [1]
=> [2]
Enter fullscreen mode Exit fullscreen mode

I know, it's probably really exploding head moment but "working as expected :D"

Collapse
 
andevr profile image
drew

Comparing apples and oranges is how I intially thought of this when I was working through it yesterday. Try expanding the left side to apples oranges and lemons and see if that breaks your head! 😆

Collapse
 
bigspaces profile image
BigSpaces

If you could only see my LiveBook now... it is a full shopping list