optimization of list comprehensions
Ulf Wiger (AL/EAB)
ulf.wiger@REDACTED
Tue Mar 7 09:17:59 CET 2006
Richard A. O'Keefe wrote:
> In fact, I spent about 20 minutes looking at foldl calls in
> the OTP sources, and *most* of them had complex functions and
> list arguments that were just simple variable names.
Let me then provide a more interesting example.
Based on (and supposedly equivalent to) real-life code,
but never compiled nor tested:
mk_tops(TIds1, TIds2, Dir, SId)
when is_list(TIds1), is_list(TIds2) ->
[#ctxtTop{frTId = TId1, toTId = TId2,
dir = Dir, strId = SId} ||
TId1 <- TIds1,
TId2 <- TIds2,
TId1 =/= TId2].
expand(Tops, TIds) ->
lists:foldr(
fun(#ctxtTop{frTId = '*', toTId = '*', dir = Dir, strId = SId}, Acc)
->
Acc ++ mk_tops(TIds, TIds, Dir, Sid);
(#ctxtTop{frTId = T1, toTId = '*', dir = Dir, strId = SId}, Acc)
->
Acc ++ mk_tops([T1], TIds, Dir, SId);
(#ctxtTop{frTId = '*', toTId = T1, dir = Dir, strId = SId}, Acc)
->
Acc ++ mk_tops(TIds, [T1], Dir, SId)
end, [], Tops).
or, rewritten without ++:
expand(Tops, TIds) ->
lists:foldl(
fun(#ctxtTop{frTId = '*', toTId = '*', dir = Dir, strId = SId}, Acc)
->
mk_tops(TIds, TIds, Dir, Sid, Acc);
(#ctxtTop{frTId = T1, toTId = '*', dir = Dir, strId = SId}, Acc)
->
mk_tops([T1], TIds, Dir, SId, Acc);
(#ctxtTop{frTId = '*', toTId = T1, dir = Dir, strId = SId}, Acc)
->
mk_tops(TIds, [T1], Dir, SId, Acc)
end, [], Tops).
mk_tops(TIds1, TIds2, Dir, SId, Acc) ->
lists:foldl(
fun(TId1, Acc1) ->
lists:foldl(
fun(TId2, Acc11) when TId1 =/= TId2 ->
[#ctxtTop{frTId = TId1, toTId = TId2,
dir = Dir, strId = SId} | Acc11]
end, Acc1, TIds2)
end, Acc, TIds1).
I have no own idea on how to improve it, with or without
folding lcs.
Regards,
Ulf W
More information about the erlang-questions
mailing list