[erlang-questions] Beginner

Andreas Hillqvist <>
Mon Feb 25 12:37:15 CET 2008


You could write:
    min([H]) ->
insted of:
    min([H | []]) ->


An alternativ is to make the function tail-recursive:
    min([H | T]) ->
        min(H, T);
    min(N) when number(N) ->
        N.

    min(Min, [H | T]) when H > Min ->
        min(Min, T);
    min(Min, [H | T]) when H =< Min ->
        min(H, T);
    min(Min, []) ->
        Min.

(The code is untested.)


Kind regard
Andreas Hillqvist

2008/2/25, nick james <>:
>
>
>
> Hi,
>
>     I have a program which results in a run time error I don't understand.
> The program is:
>
>
>
> -module(lists1).
>
> -export([min/1]).
>
>
>
> min(N) when number(N) ->
>
>     N;
>
>
>
> min([H|[]]) ->
>
>     H;
>
>
>
> min([H|T]) ->
>
>     tailMin = min(T),
>
>     if
>
>         tailMin > H ->
>
>             H;
>
>         tailMin =< H ->
>
>             tailMin
>
>     end
>
> .
>
>
>
> And the output is:
>
> Eshell V5.6  (abort with ^G)
>
> 1> c(lists1).
>
> {ok,lists1}
>
> 2> lists1:min(1).
>
> 1
>
> 3> lists1:min([1]).
>
> 1
>
> 4> lists1:min([1,2]).
>
> ** exception error: no match of right hand side value 2
>
>      in function  lists1:min/1
>
> 5>
>
>
>
> My expectation is that lists1:min([1,2]) would be picked up by min([H|T]) .
> Can anyone enlighten me?
>
>
>
> Nick James
> Cadar Measurement Solutions Ltd
> tel 08453 708 709
> Registered in England, no.2027817, 100 Fitzwalter Road, Sheffield S2 2SP
>
>
> _______________________________________________
> erlang-questions mailing list
> 
> http://www.erlang.org/mailman/listinfo/erlang-questions
>



More information about the erlang-questions mailing list