Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return the number of elements?

Tags:

erlang

I have to write a function that takes a list of integers as a parameter & returns the number of integers from the list that are less than 1. What I have so far is a function that just returns how many integers in the list. I am not sure where/if I'm supposed to put a if statement and counter to only return how many integers are less than 1.

-export([num/1]).

num([]) -> 0 ;
num(L) -> num(L,0).

num([],Len) -> Len;
num([_|T],Len) ->
    num(T,Len+1).
like image 966
AaronGarcia Avatar asked Nov 28 '22 14:11

AaronGarcia


2 Answers

Your code is almost there. Key skill to learn: guard

-export([num/1]).

num([]) -> 0;
num(NUMS) ->
        num(NUMS, 0).

num([H|L], Count) when H < 1 ->  %% use of guard
        num(L, Count+1);
num([_|L], Count) ->
        num(L, Count);
num([], Count) ->
        Count.
like image 27
Anthony Kong Avatar answered Dec 05 '22 01:12

Anthony Kong


You can use length() to find the length of a list, and can use list comprehensions to filter your list.

num(L) -> length([X || X <- L, X < 1]).

Working example:

% list counter program
-module(listcounter).
-export([printnum/0, num/1]).

printnum() ->
    L = [1,2,3,0,0],
    io:fwrite("List size: ~p\n",[num(L)]).

num(L) ->
    length([X || X <- L, X < 1]).
like image 81
kmac Avatar answered Dec 05 '22 02:12

kmac