0

Erlang newbie here. I am from a Java background and am finding Erlan rather interesting. Am following the excellent book "Learn You some Erlang".

Here's an example for recursion as given in the book for reversing the order of a List:

tail_reverse(L) -> tail_reverse(L,[]).

tail_reverse([],Acc) -> Acc;
tail_reverse([H|T],Acc) -> tail_reverse(T, [H|Acc]).

This works as expected. However, if I changed the code to:

tail_reverse(L) -> tail_reverse(L,[]).

tail_reverse([],_) -> [];
tail_reverse([H|T],Acc) -> tail_reverse(T, [H|Acc]).

this now always returns [] irrespective of the contents of the List passed. So it seems that the line tail_reverse([],_) -> []; is the one getting called. However, my understanding is that it should be called only if the first parameter is empty and _ is just a placeholder.

What am I missing here?

imme
  • 299
  • 1
  • 4
  • 8

2 Answers2

3

This line:

tail_reverse([], Acc) -> Acc

is supposed to return the accumulating argument Acc when the processed list becomes empty. You replaced it with:

tail_reverse([], _) -> []

which is executed in the same case (the bottom of the recursion), but ignores the previously done work and returns the empty list.

As for the _ variable, it has not much to do with your problem, but it's explained in this answer.

Community
  • 1
  • 1
bereal
  • 32,519
  • 6
  • 58
  • 104
  • Ah! dumb of me to not see that! Need to spend more time getting used to the Erlang code/syntax. Thanks! – imme Feb 19 '15 at 10:43
0

@bereal's answer is correct. However, I am going to provide my own answer to general question of "How does the _ variable work in Erlang. I recently wrote a blog post on the _ variable:

The anonymous variable is denoted by a single underscore (_). The anonymous variable is used when a variable is required but the value needs to be ignored. The anonymous variable never actually has the value bound to it. Since the value is never bound it can be used multiple times in a pattern and each time it is allowed to match a different value. Example:

1> {_, _} = {foo, bar}.
{foo, bar}
2> _.
* 1: variable '_' is unbound 
4> {_, Second} = {foo, bar}.
{foo, bar}
5> _.
* 1: variable '_' is unbound 
6> Second.
bar

More is available here: http://stratus3d.com/blog/2014/11/05/everything-you-need-to-know-about-erlangs-magic-variable/

Stratus3D
  • 4,648
  • 4
  • 35
  • 67