4
$\begingroup$

This question already has an answer here:

I have some function which take List as input.

f[l_List]:=someActions[l]

I need apply this function to a list of lists. Now I use this approach

lst = {{1, 2}, {3, 4}};
f /@ lst
(*{someActions[{1, 2}], someActions[{3, 4}]}*)

But as we know Map over list is slower than using function with attribute Listable.

When I set attribute Listable to my function I get not expected result:

SetAttributes[f, Listable]
f[lst]
(*{{f[1], f[2]}, {f[3], f[4]}}*)

How can I use attribute Listable with function which take a list of lists as input?

$\endgroup$

marked as duplicate by Kuba, Karsten 7., gpap, bbgodfrey, m_goldberg Mar 2 '15 at 13:43

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • 5
    $\begingroup$ Possible duplicate: (33046). Leonid explains the performance issues of Listable here: (35150) $\endgroup$ – Mr.Wizard Sep 12 '14 at 9:13
1
$\begingroup$

You can't do this. If correct behaviour is

f[{{1,2},{3,4}}] -> {f[{1,2}],f[{3,4}]}

then what is correct behaviour for

f[{1,2}]

??? Clearly the second expression has no idea that it came from a previous application of f unless you find some way to tell it.

Map is the simple and correct way of achieving what you want; I don't believe that it is generally slower than Listable. If you really want to use Listable I suggest you change the Head of the inner list to something other than List, e.g. h:

SetAttibutes[f, Listable]
lst = {{1, 2}, {3, 4}};
lst = h @@@ lst ;
f[lst]
(* {f[h[1,2]], f[h[3,4]]} *)
$\endgroup$

Not the answer you're looking for? Browse other questions tagged or ask your own question.