1
$\begingroup$

The following function is supposed to pick the element of the list with highest weight, i.e., with Thread [f[{{a,1},{b,2}}]] it should make the variables initialvls={b,2}, m=2.

initialvls = {};
m = 0;
f[x_] := Module[{},
  If[x[[2]] > m,
    m = x[[2]];
    initialvls = x
    ];
  ]

I dont know anything about the inner workings of mathematica. But I would expect the thread to apply first f to {a,1},and put m=1, and initialvls={a,1}. Afterwards it would apply f to {b,2}, and so on... However, my function doesn't seem to do what I want.

Any help would be appreciated.

$\endgroup$
  • $\begingroup$ What about, from your other question, initialvls = First@Cases[#, {_, Max@#[[All, 2]]}] &@{{a, 1}, {b, 2}}; m = initialvls[[2]]? $\endgroup$ – Aisamu Dec 2 '14 at 18:38
  • $\begingroup$ @Aisamu that question is about efficiency. this is how to work with thread function, and global variables. $\endgroup$ – An old man in the sea. Dec 2 '14 at 19:19
  • $\begingroup$ (1) Thread does not have any HoldXXX attribute so it's argument is evaluated first. It's argument is f[{{a,1},{b,2}}]. f[whatever] returns unevaluated. Ergo Thread sees Null. (2) A simple Print statement would have made this clear or at least made it less mysterious. $\endgroup$ – Daniel Lichtblau Dec 2 '14 at 20:03
1
$\begingroup$
initialvls = {};
m = 0;
f[x_] := Module[{}, If[x[[2]] > m, m = x[[2]]; initialvls = x];]

Thread[ff[{{a, 1}, {b, 2}}]] /. ff -> f;
initialvls
(* {b, 2} *)
m
(* 2 *)

or

initialvls = {};
m = 0;
f[x_] := Module[{}, If[x[[2]] > m, m = x[[2]]; initialvls = x];]

Thread[Hold[f][{{a, 1}, {b, 2}}]] // ReleaseHold;
(* {b, 2} *)
m
(* 2 *)
$\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.