[erlang-questions] Idiomatic Erlang, style/performance question

Deryk Barker dbarker@REDACTED
Wed Jun 18 23:19:19 CEST 2008


Circular Function wrote:
> Is there a styleguide somewhere on Erlang? Im currently going through 
> the Erlang reference manual and you can see some examples, are those 
> generally referred to as idiomatic Erlang?
>
> Some examples of implementations of the power-function below.
> The last function someone on the mailing list provided as a correction 
> to the second one.
> The first one uses pattern matching and guard sequences right? Is this 
> a good way? I dont quite understand the advantage of the last function.
> However, the shell complains about
> 88> c(mymath).
> ./mymath.erl:24: Warning: variable 'N' is unused
> {ok,mymath}
> Which is the powerx(N, 0) -> 1; line.
> However i saw some code that used _ and i tried:
> powerx(_, 0) -> 1;
> so _ is the correct way to write this function?
>
I claim no great expertise, but I believe that

power(_N, 0) -> 1;

is the preferred style today: the compiler gives no warning but, should 
the need arise, you can refer to the first parameter as _N. (The _Name 
style also allows for name which have documentary value)

>
> Hmm while writing I got a thought. Is the last function 
> tail-recursive? I have only heard that term but never used it.
> Is tail-recursion faster or uses less memory, what is the 
> advantage/disadvantage?
>
> power(N, P) when is_integer(N), N >= 0 ->
>         ipower(N, P, 1);
>     power(N, P) when is_integer(N), N < 0 ->
>         1/ipower(-N, P, 1).
>
>     ipower(0, _, R) -> R;
>     ipower(N, P, R) -> ipower(N-1, P, R*P).
>
>
Yup, this looks tail recursive, because the recursive call to ipower is 
the last thing in the function.

TR functions can run in constant stack space; to write a server you must 
use tail recursion.

-- 
|Deryk Barker, Computer Science Dept. | Music does not have to be understood|
|Camosun College, Victoria, BC, Canada| It has to be listened to.           |
|email: dbarker@REDACTED         |                                     |
|phone: +1 250 370 4452               |         Hermann Scherchen.          |





More information about the erlang-questions mailing list