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