[erlang-questions] conses in erlang?

Lev Walkin <>
Wed Jul 2 11:03:51 CEST 2008


not norwegian swede wrote:
>   can i use conses in erlang?
> like in scheme, then i only need one function. is the range func in 
> erlang ood erlang-style or is there a better way to do it?
> 
> (define (seq a b)
>     (if (< a b)
>         (cons a (seq (+ a 1) b))
>         '()))
> 
> -module(test).
> -export([range/2]).
>      
> range(Start, End) when Start < End, is_integer(Start), is_integer(End) ->
>     seq(Start, End, []).
> 
> seq(Start, End, List) ->
>     if Start =< End ->
>         seq(Start + 1, End, List ++ [Start]);
>     true ->
>     List
> end.


seq(Start, End) when is_integer(Start), is_intger(End) ->
	seq(End, Start, []).

seq(End, Start, Acc) when Start >= End ->
	seq(End - 1, Start, [End|Acc]);
seq(_End, _Start, Acc) -> Acc.


this approach also has a linear complexity, instead of being O(N^2)
in your cas.

-- 
vlm



More information about the erlang-questions mailing list