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]]).

Site Footer

Sliding Sidebar

About Me

About Me

For whom this blog for?

For those who are interested in modern Internet technologies, IT business, startups, management, quality control, personal effectiveness, motivation. Here I write about what is interesting, about problems I faced and solutions I found. I hope it will be interesting to you either.

What motivates me to write?

The desire to improve, to study deeper topics that interest me. Find people with similar problems and tasks, together look for ways out and solutions.

Feel free to contact if you have anything to say to me

Old Flash site with my artistic works and misuc.