1
$\begingroup$

Problem: How to map a function onto a list. My (example input:

mylist = {{1, 2}, {3, 4}}
gg[x_, y_] := {N[x + y], N[x y]}
Map[gg, mylist]

Expected output:

{{3., 2.}, {7., 12.}}

Actual output:

{gg[{1, 2}], gg[{3, 4}]}

How do I get gg[.] to give a numerical (function evaluated) output of mylist?

$\endgroup$
  • $\begingroup$ try gg[{x_, y_}] := {N[x + y], N[x y]} $\endgroup$ – user42582 May 9 '18 at 20:48
  • 2
    $\begingroup$ gg @@@ mylist. But if you need to use Map then Apply[gg] /@ mylist. $\endgroup$ – Kuba May 9 '18 at 20:50
  • 2
    $\begingroup$ Scan vs. Map vs. Apply - quite broad but should answer. $\endgroup$ – Kuba May 9 '18 at 20:57
  • $\begingroup$ Not sure why, but that works. Thanks $\endgroup$ – mark r May 9 '18 at 21:24
3
$\begingroup$

As mentioned in the comments by Kuba, you should use

gg @@@ mylist

Indeed, this is precisely raison d'être of @@@. If you want to use Map, then Kuba suggests to use the operator form of @@, to wit,

Apply[gg] /@ mylist

Finally, let me mention that if you insist on using Map, then you should redefine the function gg into (hat tip to kglr)

gg[{x__}] := {N[+x], N[1 x]}

If you do so, then Map[gg, mylist] yields your expected output.

$\endgroup$
  • $\begingroup$ Fun fact: the expression Plus[x] can be simplified into +x, but Times[x] cannot be replaced by *x. Seems inconsistent to me -- both Plus and Times are OneIdentity, and I'd expect both of them to behave similarly. Wonder why they don't here... $\endgroup$ – AccidentalFourierTransform May 9 '18 at 22:29
  • $\begingroup$ {+##, 1 ##} & @@@ mylist ? $\endgroup$ – kglr May 9 '18 at 22:34
  • $\begingroup$ @kglr Ah, perfect. I was actually about to post a question on why * is not allowed to be unary as opposed to +. Your trick works just fine, thanks! $\endgroup$ – AccidentalFourierTransform May 9 '18 at 22:41
1
$\begingroup$
mylist = {{1, 2}, {3, 4}}
gg[x_, y_] := {N[x + y], N[x y]}
Map[gg[#[[1]],#[[2]]]&, mylist]
$\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.