4
$\begingroup$

I have the following function:

magicFunction[ lst_, val_ ] := Fold[ ((#2 < val) && #1) &, True, lst ]

It works

In[]=:magicFunction[{6,7},9] 
Out[]= True

I want to Map the function. To do it I use Thread.

If I use Thread for a noname function with the list I want to map, the following is produced:

In[]:= Thread[f[{{6,7},{2,3},{1,2}},{9, 10,5}]]
Out[]= {f[{6,7},9],f[{2,3},10],f[{1,2},5]}

That is exactly what I want to do.

However, when I use magicFunction that is not what I get. If I use magicFunction I should get the following:

Out[]:= {magicFunction[{6,7},9],magicFunction[{2,3},10],magicFunction[{1,2},5]}

which then evaluates to:

Out[]:= {True, True, True}

However what I get is the following:

In[]:= Thread[magicFunction[{{6,7},{2,3},{1,2}},{9, 10,5}]]

Out[]:= {1,2}<{9,10,5}&&{2,3}<{9,10,5}&&{6,7}<{9,10,5}

Does anybody know what I m doing wrong?

Thanks in advance!

$\endgroup$
7
$\begingroup$

Your issue is that magicFunction evaluated before Thread could do anything. One idea to avoid this is to use Unevaluated:

Thread[Unevaluated @ magicFunction[{{6,7},{2,3},{1,2}},{9,10,5}]]

{True, True, True}

Another idea is to add an argument restriction to your magicFunction. Since Less only makes sense for numeric quantities, you can use:

Clear[magicFunction]
magicFunction[lst_, val_?NumericQ] := Fold[((#2<val)&&#1)&,True,lst]

Then:

Thread[magicFunction[{{6,7},{2,3},{1,2}},{9,10,5}]]

{True, True, True}

$\endgroup$
6
$\begingroup$

You can use MapThread:

MapThread[magicFunction, {{{6, 7}, {2, 3}, {1, 2}}, {9, 10, 5}}]

{True, True, True}

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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