Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print each element from a list in Erlang

Tags:

list

erlang

I have created a function which will check if there is any even number in a given list, and then the even numbers are collected in a list. However I am stuck at where I want to print out each even number from that list in 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 am thinking maybe list comprehensions, but I also want to try it without the list comprehensions.

like image 979
maoyi Avatar asked Sep 18 '15 18:09

maoyi


2 Answers

You're very close, but you have a couple suspect function clauses here:

  • The second clause, with an argument of [H|[]], isn't needed because the following clauses with the [H|T] arguments will handle the case when T is [].
  • The last clause needs no guard since the third one has already skipped every odd value. Note that the list it constructs, [H|even_print(T)], just gets dropped here since you're not using it. It needs to be the last expression in the function so it's treated as the return value. Also, the last argument to io:format/2 there must be a list, plus the format string is wrong because it contains no directive to print that argument.

Making these changes, we wind up with this:

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

If we run it in the Erlang shell, we get:

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

If you don't want the printing, just remove the io:format/2 call.

like image 57
Steve Vinoski Avatar answered Sep 21 '22 13:09

Steve Vinoski


This is one way to do it:

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

In my Erlang shell this outputs:

31> c(main).
{ok,main}
32> main:even_print([1,2,3,4,5,6]).
printing: 2
printing: 4
printing: 6
ok
33>
like image 23
jpw Avatar answered Sep 20 '22 13:09

jpw