Erlang. Упражнения (продолжение). Манипулирование списками.

Exercise 3-5: Manipulating Lists

Write a function that, given a list of integers and an integer, will return all integers
smaller than or equal to that integer.

Example:
filter([1,2,3,4,5], 3) ⇒ [1,2,3].

Write a function that, given a list, will reverse the order of the elements.

Example:
reverse([1,2,3]) ⇒ [3,2,1].

Write a function that, given a list of lists, will concatenate them.

Example:
concatenate([[1,2,3], [], [4, five]]) ⇒ [1,2,3,4,five].

Hint: you will have to use a helpfunction and concatenate the lists in several steps.
Write a function that, given a list of nested lists, will return a flat list.

Example:
flatten([[1,[2,[3],[]]], [[[4]]], [5,6]]) ⇒ [1,2,3,4,5,6].

Hint: use concatenateto solve flatten

Мой вариант решения:

-module (test3_5).
-compile(export_all).
-import (io).

filter([], _Max, Result) -> 
  Result;
filter([Head | Tail], Max, Result) when Head >= Max ->  
  filter(Tail, Max, Result ++ [Head]);
filter([_Head | Tail], Max, Result) ->  
  filter(Tail, Max, Result).
filter(List, Max) -> 
  filter(List, Max, []).

reverse([], Result) ->
  Result;
reverse([Head | Tail], Result) ->
  reverse(Tail, [Head] ++ Result).
reverse(List) ->
  reverse(List, []).

concatenate(L) ->
  concatenate(L, []).
concatenate([], Result) ->
  Result;
concatenate([Head | Tail], Result) ->
  concatenate(Tail, Result ++ Head).

flatten(List) ->
  flatten(List, []).
flatten([], Result) ->
  Result;
flatten([Head | Tail], Result) ->
  flatten(Tail, Result ++ flatten(Head));
flatten(Value, Result) ->
  Result ++ [Value].

test() ->
  filter([1,2,3,4,5],3),
  reverse([1,2,3]),
  concatenate([[1,2,3], [], [4, five]]),
  flatten([[1,[2,[3],[]]], [[[4]]], [5,6]]).

Comments

comments


Bookmark and Share