I am interested in mapping a function, f
over a (long) list which contains duplicates.
Since this function takes a while to evaluate I would like to make use of this duplication to speed up the mapping.
Attempt
Let us say my list is
list = {a, a, b, a, c, b}
my purpose is to map f
over list
efficiently.
I have defined a function
MapDuplicate[f_, list_] := Module[{ff, list1, ulist},
list1 = ff /@ list; (* ff is dummy f *)
ulist = Union[list]; (* the reduced list *)
rr = Dispatch[Thread[(ff /@ ulist) -> (f /@ ulist)]];
list1 /. rr]
which does the trick,
MapDuplicate[f1, list]
(* {f1(a),f1(a),f1(b),f1(a),f1(c),f1(b)} *)
but I strongly suspect there is a more elegant (using Ordering
? SparseArray
?) of doing this.
Question
Any idea on how to do this more efficiently (e.g. without duplicating the list) My apologies in advance if the answer turns out to be trivial.
f[x_]:=f[x]= your definition
used withMap
:f/@list
$\endgroup$Dispatch
, etc) may actually make things slower for numerical lists when your function is compilable, sinceMap
auto-compiles and switching to memoization etc you will lose that advantage (not to detract from the suggestions to use memoization etc, since those are the right things to do generically). $\endgroup$