[erlang-questions] or?

Richard A. O'Keefe <>
Thu Jun 19 02:31:52 CEST 2008


On 19 Jun 2008, at 4:44 am, Circular Function wrote:
>
> fib(N) ->
>         if
>                 N > 1 ->
>                         fib(N-1) + fib(N-2);
>                 N == 1 or N == 0 ->
>                         N
>         end.
>
> it doenst work, how do i use or?

Don't.
Don't use 'and' or 'or' in Erlang without thinking about whether
they really REALLY do what you want.  You almost always want
something else.
When you have determined that they really are what you want,
don't use them anyway, because people reading your code will
_think_ you made a mistake and should have used 'andalso' or
'orelse' instead.

>
> http://www.erlang.org/doc/reference_manual/part_frame.html
> doesnt provide an actual example of how to use it.

Section 6.24 of that very manual tells you exactly what to do
in its very first paragraph.  You need

	fib(N) ->
	    if N > 1 -> fib(N-1) + fib(N-2)
	     ; N == 1 ; N == 0 -> N
	    end.

If you know that N is an integer, it is simpler to do

	fib(N) ->
	    if N >  1 -> fib(N-1) + fib(N-2)
	     ; N >= 0 -> N  % 0 or 1
	    end.

In this case, it would be better to do

	fib(N) when is_integer(N), N >= 0 ->
	    fib_aux(N).

	fib_aux(N) when N > 1 -> fib_aux(N-1) + fib_aux(N-2);
	fib_aux(N)            -> N.

Better still, of course, would be to use the standard
linear-time tail-recursive version, or even better, the
less well known logarithmic time version (an approach
that works for other recurrences as well).







More information about the erlang-questions mailing list