6
$\begingroup$

The gist of this question is to find a function that takes a list of functions and a list of arguments and wraps each argument with the corresponding function e.g. someFunction[{f1, f2, f3}, {arg1, arg2, arg3}] should evaluate to {f1[arg1], f2[arg2], f3[arg3]]}. Of the given answers I find none that is really readable and I though that the undeservedly seldom used Thread might offer a better solution. What it does is that it pairs arguments from one list with arguments from a second list

Thread[someHead[{a, b, c}, {x, y, z}]]
(* {someHead[a, x], someHead[b, y], someHead[c, z]} *)

The snag here is someHead unfortunately. I couldn't find a nice function someHead[f, arg] that evaluates to f[arg] i.e. applies f as a Head to arg and I started wondering why this is.

This brings me to my question: Is there a function/expression similar to Apply, Map, Composition and friends for basic function application, i.e. wrapping an expression with a Head? Compare for instance

Thread[Composition[{a, b, c}, {x, y, z}]]
(* {a@*x, b@*y, c@*z} *)

This leads to a philosophical question: In functional programming language, should there be a function for applying a function?

$\endgroup$
1
  • $\begingroup$ A hack is Thread[Inactivate[(#1@#2 &)][{a, b, c}, {x, y, z}]] // Activate by the way. For some reason Thread[(#1@#2 &)[{a, b, c}, {x, y, z}]] does not work. $\endgroup$
    – Sascha
    Jan 3, 2018 at 9:31

4 Answers 4

9
$\begingroup$
MapThread[#[#2] &, {{a, b, c}, {x, y, z}}]

or

SetAttributes[someHead, Listable];
someHead[f_, arg_] = f[arg];

someHead[{a, b, c}, {x, y, z}]

{a[x], b[y], c[z]}

$\endgroup$
1
  • $\begingroup$ You might (also) want to post these as answers to the original question I referenced in my question. $\endgroup$
    – Sascha
    Jan 3, 2018 at 10:53
3
$\begingroup$

You can use the deprecated since M2 (but still working) function Compose for this:

Thread[Unevaluated @ Compose[{a, b, c}, {x, y, z}]]

{a[x], b[y], c[z]}

Alternatively, you could use:

someFunction = Thread @* Unevaluated @* Compose;

someFunction[{a, b, c}, {x, y, z}]

{a[x], b[y], c[z]}

$\endgroup$
2
$\begingroup$

Version 11.3 introduces Construct

Construct[f,x] gives f[x].

Two possible answers using the new function are

Thread[Unevaluated@Construct[{a, b, c}, {x, y, z}]]

and

MapThread[Construct, {{a, b, c}, {x, y, z}}]
$\endgroup$
0
$\begingroup$

Almost equivalent to MapThread method by Coolwater:

Inner[#@#2 &, {f, g, h}, {x, y, z}, List]
$\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.