[erlang-questions] power(N,P), cant get it to work

Andreas Hillqvist andreas.hillqvist@REDACTED
Wed Jun 18 08:36:00 CEST 2008


I can not see how the code will terminate for a negative N?
        power(N, P) when is_integer(N), N < 0 ->
            1/ipower(-1 * N, P, 1).
Or can "-" be used as an unary operation:
        power(N, P) when is_integer(N), N < 0 ->
            1/ipower(-N, P, 1).


Kind regards
Andreas Hillqvist

2008/6/18, Richard A. O'Keefe <ok@REDACTED>:
> This is another case of missing 'end's.
>
> power/2 would be more cleanly written as
>
>        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).
>
> (a) use pattern matching and guards
> (b) common case first [power/2]
>     base case first [ipower/3]
> (c) tail recursion
> (d) don't keep on checking for < 0
> (e) help Dialyzer help you (the is_integer/1 tests).
> (f) public checks [power/2] private trusts [ipower/3].
>
> It would be even better if written to take logarithmic time,
> but that's another story.
>
> While we're at it,
>
>        fac(N) when is_integer(N), N >= 1 ->
>            ifac(N, 1);
>        fac(0) -> 1.
>
>        ifac(1, R) -> R;
>        ifac(N, R) -> ifac(N-1, R*N).
>
> The same ideas apply.
>
> _______________________________________________
> erlang-questions mailing list
> erlang-questions@REDACTED
> http://www.erlang.org/mailman/listinfo/erlang-questions
>



More information about the erlang-questions mailing list