[erlang-questions] Can not understand the example.

Ulf Wiger (TN/EAB) ulf.wiger@REDACTED
Fri Jan 19 19:09:19 CET 2007


Perhaps you should read the on-line erlang course:
 
http://www.erlang.org/course/course.html
 
Especially:
 
http://www.erlang.org/course/sequential_programming.html
 
To answer your question, the following quote from the above course:
 
 Clauses are scanned sequentially until a match is found.
 
Perhaps another missing detail is that the return value of a function is
the result of the last expression. In the case of fac(1), it's the
number 1.
 
Also from the above course:
 

Evaluation example

	factorial(0) -> 1;
	factorial(N) -> 
		N * factorial(N-1)

	> factorial(3)
		matches N = 3 in clause 2
		== 3 * factorial(3 - 1)
		== 3 * factorial(2)
		matches N =2 in clause 2 
		== 3 * 2 * factorial(2 - 1)
		== 3 * 2 * factorial(1)
		matches N = 1 in clause 2
		== 3 * 2 * 1 * factorial(1 - 1)
		== 3 * 2 * 1  * factorial(0)
		== 3 * 2 * 1  * 1 (clause 1)
		== 6

 
BR,
Ulf W


________________________________

	From: erlang-questions-bounces@REDACTED
[mailto:erlang-questions-bounces@REDACTED] On Behalf Of LUKE
	Sent: den 19 januari 2007 16:36
	To: erlang-questions@REDACTED
	Subject: [erlang-questions] Can not understand the example.
	
	
	-module(tut1).
	-export([fac/1]).
	
	fac(1) ->
	    1;
	fac(N) ->
	    N * fac(N - 1).
	==================================
	How can i know the function will STOP at N=1?
	
	===================================
	-module(tut4).
	
	-export([list_length/1]).
	
	list_length([]) ->
	    0;    
	list_length([First | Rest]) ->
	    1 + list_length(Rest).
	
	===================================
	How can i know the loop will stop when First=[ ]?
	===================================
	How to explain theses code?
	 
	In perl:
	for (my $i=0;$i<=10;$i++){
	....
	}
	 
	It is very clear the process will stop when $i > 10.
	 
	 

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20070119/4e5c0ae7/attachment.htm>


More information about the erlang-questions mailing list