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

Richard A. O'Keefe <>
Wed Jun 18 04:04:18 CEST 2008

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.

More information about the erlang-questions mailing list