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.
You're very close, but you have a couple suspect function clauses here:
[H|[]]
, isn't needed because the following clauses with the [H|T]
arguments will handle the case when T
is []
.[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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With