Noob - Getting Started Infinte Loop?
Per Gustafsson
per.gustafsson@REDACTED
Wed Aug 30 13:22:29 CEST 2006
fbg111 wrote:
> Hi all, I'm an Erlang noob working through the getting started material at
> erlang.org, and I have a question about a problem that's occuring with my
> code. If this isn't the appropriate place for this question, my apologies
> for wasting the bandwidth, please point me in the right direction.
> Otherwise, running the function listlen([1,2,...n]) crashes the Erlang
> emulator in WinXP. However, I can't see the difference b/t my code and the
> example code:
>
> http://erlang.org/doc/doc-5.5/doc/getting_started/seq_prog.html#2.5 Example
> code:
>
>
>
>>The following example shows how we find the length of a list:
>>
>>-module(tut4).
>>-export([list_length/1]).
>>
>>list_length([]) ->
>> 0;
>>list_length([First | Rest]) ->
>> 1 + list_length(Rest).
>>
>>Compile (file tut4.erl) and test:
>>29> c(tut4).
>>{ok,tut4}
>>30> tut4:list_length([1,2,3,4,5,6,7]).
>>7
>>
>
>
> My code:
>
>
>
>>-module(tut).
>>-export([double/1,fac/1,mult/2,convert/1,conv/2,listlen/1]).
>>
>>double(X) -> 2 * X.
>>fac(0) -> 1;
>>fac(N) -> N * fac(N-1).
>>mult(X,Y) -> X*Y.
>>conv(M,toInch) -> M/2.54;
>>conv(N,toCentimeter) -> N*2.54.
>>convert({M,centimeters}) -> {M/2.54,inches};
>>convert({M,inches}) -> {M*2.54,centimeters}.
>>listlen([]) -> 0;
>>listlen([First|TheRest]) -> 1 + listlen([TheRest]).
>>
listlen should be defined as:
listlen([]) -> 0;
listlen([First|TheRest]) -> 1 + listlen(TheRest).
because in your definition the recursive call is always made with a list
consisting of one element ([TheRest]) because of this your function does
not terminate and it runs out of memory.
Per
More information about the erlang-questions
mailing list