List Patterns in Elixir

Hi,

I am trying to solve some problems of “Programming Elixir > 1.6” by Dave Thomas and on page 251 “lists/swap.exs” programming is not working on my end. when I try to execute this program I get the following error.

Code:

defmodule Swapper do
  def swap([]), do: []
  def swap([a, b | tail]), do: [b, a | swap(tail)]
  def swap([_]), do: raise("Can't swap a list with an odd number of elements")
end

Error:

 Swapper.swap [1, 2, 3]
** (RuntimeError) Can't swap a list with an odd number of elements
    swap.ex:6: Swapper.swap/1
    swap.ex:5: Swapper.swap/1

What do you mean “not working”? From what I see it perfectly works, entering the third clause when the number of elements in the list is odd.

3 Likes

The compiles should just show this line right

** (RuntimeError) Can't swap a list with an odd number of elements

why is it showing this error

swap.ex:6: Swapper.swap/1
swap.ex:5: Swapper.swap/1

If you want it to print a message instead of raising an exception, change it to:

- raise("Can't swap a list with an odd number of elements")
+ IO.puts("Can't swap a list with an odd number of elements")
1 Like

The output you got is the expected and correct one.

In the book they probably only printed the first line of the output to save space.

The two lines bellow in your output is the stack trace of the exception you received.

4 Likes

That would not only print the error, but even worse return [2, 1 | :ok]

4 Likes

Yes ! Like @Jcambass said. This is the stack trace of the error you raise.

The stack trace shows the sequence of calls that leads to the error.

First you call swap.ex:5: Swapper.swap/1 which call Swapper.swap/1 recursively, leading to the execution of swap.ex:6: Swapper.swap/1.

Note the line change, the first one (in a stack sense, so bottom first) is line 5 and de last one is line 6, and on the execution of swap.ex:6: Swapper.swap/1 is where the error is raised.

2 Likes

The result is more terrible now … its shows [2, 1 | :ok]

There cannot be result when you try to swap elements in a list having odd numbers of elements.

The original version raised an exception, which is completely fine, but your comments contained the claim to avoid the stacktrace (meaning not to raise an exception.) I proposed a quick dirty hack to not raise an exception. Of course, the result still has no meaning, because it’s not defined for such lists.

2 Likes

Yes, you are absolutely right.