loop_lists function should behave as follows:
1> loop_lists([[spanner, screwdriver],[monday,tuesday,wednesday]]). [[spanner,monday], [spanner,tuesday], [spanner,wednesday], [screwdriver,monday], [screwdriver,tuesday], [screwdriver,wednesday]] |
1> loop_lists([[a,b],[x,y],[1,2,3]]). [[a,x,1], [a,x,2], [a,x,3], [a,y,1], [a,y,2], [a,y,3], [b,x,1], [b,x,2], [b,x,3], [b,y,1], [b,y,2], [b,y,3]] |
> lists:map(MyFunction, loop_lists([ProductList,DayList])). > [MyFunction(ProdDay) || ProdDay <- loop_lists([ProductList,DayList])]. |
loop_lists([]) -> [[]]; loop_lists([H|[]]) -> [[X] || X <- H]; loop_lists([H|T]) -> [[X|Y] || X <- H, Y <- loop_lists(T)]. |
loop_lists(L) -> loop_lists(L, []). loop_lists([], Acc) -> Acc; loop_lists([H|T], []) -> loop_lists(T, [[X] || X <- H]); loop_lists([H|T], Acc) -> loop_lists(T, [lists:append(X, [Y]) || X <- Acc, Y <- H]). |
lists:append, which may have a significant performance impact with larger lists.
loop_lists(L) -> loop_lists(lists:reverse(L), []). loop_lists([], Acc) -> Acc; loop_lists([H|T], []) -> loop_lists(T, [[X] || X <- H]); loop_lists([H|T], Acc) -> loop_lists(T, [[X|Y] || X <- H, Y <- Acc]). |
lists:reverse once on the initial source list so that the target lists are accumulated in the correct order.
This version is probably the best of attempts 1-3, but still requires some amount of memory to hold the resulting looping list.
Fun1 = fun(Element1) ->
Fun2 = fun(Element2) ->
Fun3 = fun(Element3) ->
DoSomething([Element1, Element2, Element3])
end,
lists:foreach(Fun3, List3)
end,
lists:foreach(Fun2, List2)
end,
lists:foreach(Fun1, List1). |
lists:map(fun(X) -> DoSomething(X) end, loop_lists([List1, List2, List3])). |
| CookbookForm | |
|---|---|
| TopicType: | Recipe |
| ParentTopic: | ListRecipes |
| TopicOrder: | 090 |