[erlang-questions] List comprehensions challenge ;-)

Baishampayan Ghose b.ghose@REDACTED
Wed Jan 12 10:20:04 CET 2011


> Just playing with list comprehensions...
>
> I was asking if it possible to do it without lists:sum, by using an
> anonymous function and add it directly in the list comprehensions ?
>
> 26> [A+B || A <-[1,2,3],B <- [7,8,9,10,11]].
> [8,9,10,11,12,9,10,11,12,13,10,11,12,13,14]
> 30> lists:sum([A+B || A <-[1,2,3],B <- [7,8,9,10,11]]).
> 165

I don't think it's possible since list comprehensions will always
return a list of items. The lists:sum approach is correct, but you can
also try out lists:foldl/3 for more fun (pun intended).

42> lists:foldl(fun (X, Y) -> X + Y end, 0, [A+B || A <-[1,2,3],B <-
[7,8,9,10,11]]).
165

Regards,
BG

-- 
Baishampayan Ghose
b.ghose at gmail.com


More information about the erlang-questions mailing list