Reputation: 43
I'm trying to implement a function
llen(ListOfLists)
which returns a list containing the lengths of the lists in ListOfLists. Function should use lists:map/2.
Example:
1> funs:llen([[1, 2, 3], [], [4, 5]]).
[3, 0, 2]
I know how to calculate length for one list:
list([]) -> 0;
list([_|T]) -> 1+list(T).
but i don't know how to do this for multiple lists using funs and lists.
Upvotes: 2
Views: 1160
Reputation: 48599
And when you get to list comprehensions:
53> L = [[1, 2, 3], [], [4, 5]].
[[1,2,3],[],[4,5]]
54> [length(X) || X <- L].
[3,0,2]
A list comprehension is like a for-loop in other languages, and this one reads like:
length(X) for X in L
length(X) || X <- L
The outer [ ]
serves to gather up all the results into a list.
Upvotes: 2
Reputation: 91942
lists:map/2
is a higher order function that applies a function for each element of a list. erlang:length/1
is a function that returns the length of a list.
Apply erlang:length/1
on each element of your list using lists:map/2
:
lists:map(fun erlang:length/1, [[1, 2, 3], [], [4, 5]])
Upvotes: 5