5

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).
2240
  • 1,547
  • 2
  • 12
  • 30
AaronGarcia
  • 93
  • 1
  • 1
  • 4

4 Answers4

15

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]).
kmac
  • 688
  • 4
  • 15
  • although this solution creates an intermediate list and then parse it to count the elements, the list comprehension and the bif length() seem to be really optimized, and it results that it is the fastest one – Pascal Oct 03 '14 at 05:45
6

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.
Anthony Kong
  • 37,791
  • 46
  • 172
  • 304
3

This one avoid to build an intermediate list. roughly the same than Anthony proposal using erlang library and anonymous function.

lists:foldl(fun(X,Count) when X < 1 -> Count+1; (_,Count) -> Count end,0,L).
Pascal
  • 13,977
  • 2
  • 24
  • 32
0

My solution:

get_list_size(List) ->
    get_list_size(List, 0).

get_list_size([First | Rest], Count) ->
    get_list_size(Rest, Count + 1);

get_list_size([], Count) ->
    Count.

Use:

Size = get_list_size([1, 2, 3])