Benjamin Halsted // [bgh] todo, add something clever here.

12Mar/100

Erlang Programming Exercise: 3-2

Exercise 3-2 is also 2 questions:

Write a function that returns a list of the format [1,2,..,N-1,N].

Write a function that returns a list of the format [N, N-1,..,2,1]

I've created 4 functions, create/1, create/2, reverse_create/1, and reverse_create/2. The /1 functions set up the arguments for the /2 worker functions to loop on.

-module(threetwo).
-export([create/1, reverse_create/1]).

create(1, [1|_T]=List) ->
	List;
create(Num, List) ->
	Next = Num-1,
	create(Next, [Next|List]).

create(Num) when Num > 0 ->
	create(Num, [Num]).

reverse_create_list(Num, [Num|_T]=List) ->
	List;
reverse_create_list(Num, [H|_T]=List) ->
	reverse_create_list(Num, [H+1|List]).

reverse_create(Num) when Num > 0 ->
	reverse_create_list(Num, [1]).

An example run:

4> threetwo:create(10).
[1,2,3,4,5,6,7,8,9,10]
5> threetwo:reverse_create(10).
[10,9,8,7,6,5,4,3,2,1]

The key in is to pass your target number along and to build the list from right to left. In each iteration we peak at the head of the list, modify that value and then prepend the result to the head of the full list.

[H|_T]=List

H is the first item in the list.
List is the full List.

Cheers,
Ben

Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Reddit
  • Twitter
Comments (0) Trackbacks (0)

No comments yet.


Leave a comment

(required)

No trackbacks yet.