Print each item from a list in Erlang

I created a function that will check if there is an even number in this list, and then even numbers are collected in the list. However, I am stuck in where I want to print every even number from this list on a new line.

Here is my code snippet:

even_print([])-> [];
even_print([H|[]]) -> [H];
even_print([H|T]) when H rem 2 /= 0 -> even_print(T);
even_print([H|T]) when H rem 2 == 0 -> [H|even_print(T)],
io:format("printing: ~n", H).

I think I might understand the list, but I also want to try it without understanding the lists.

+4
source share
2 answers

You are very close, but you have a couple of suspected functions:

  • A second sentence with an argument is [H|[]]not required, because the following sentences with arguments [H|T]will handle the case when Tthere is [].
  • , . , , , [H|even_print(T)], , . , . , io:format/2 , , .

, :

-module(e).
-export([even_print/1]).

even_print([])-> [];
even_print([H|T]) when H rem 2 /= 0 ->
    even_print(T);
even_print([H|T]) ->
    io:format("printing: ~p~n", [H]),
    [H|even_print(T)].

Erlang, :

3> e:even_print(lists:seq(1,10)).
printing: 2
printing: 4
printing: 6
printing: 8
printing: 10
[2,4,6,8,10]

, io:format/2.

+6

:

even_print([])-> ok;
even_print([H|T]) when H rem 2 /= 0 -> even_print(T);
even_print([H|T]) when H rem 2 == 0 ->  
     io:format("printing: ~p~n", [H]),
     even_print(T).

Erlang :

31> c(main).
{ok,main}
32> main:even_print([1,2,3,4,5,6]).
printing: 2
printing: 4
printing: 6
ok
33>
+1

Source: https://habr.com/ru/post/1608073/


All Articles