Erlang - How To Return Count/Number Of Elements

元气小坏坏 提交于 2019-12-11 04:09:05

问题


This is my very first Erlang project. Basically, 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).

回答1:


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.



回答2:


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



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


来源:https://stackoverflow.com/questions/26111962/erlang-how-to-return-count-number-of-elements

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!