1
$\begingroup$

I am trying to generate a function that applies to each argument for any number and type of arguments. The function might work like this:

m = {{1, 2}, {3, 4}}; (* matrix *)
v = {1, 2, 1}; (*a vector *)
b = 10; (* a scalar *)

f[x__] := p[x] (* not sure what the function would like but this is probably close *)

f[m, v, b] (* notice arguments are not in a list n*)
(* Out: {p[m], p[v], p[b]} (*desired output *)

How would I set up such a function? How should attributes be set?

$\endgroup$
1
  • $\begingroup$ Will the arguments stay in the order you give them? What happens when you give a List? $\endgroup$ Jun 9, 2020 at 3:05

2 Answers 2

1
$\begingroup$
ClearAll[f]
f = Map[p] @* List;

f[m, v, b]
{p[{{1, 2}, {3, 4}}], p[{1, 2, 1}], p[10]}
$\endgroup$
3
  • $\begingroup$ thank you the function model works. For a real world case I would replace p with objectName = Function[Null, SymbolName[Unevaluated[#]], {HoldFirst}]; which works fine when called directly for example x = {1,2,3} with objectName[x] but not when called from another function f[x]as in replacing p: f=Map[objectName]@*List and I can't figure out why. ?x reveals its a symbol but I get not a symbol errors when used in this model. $\endgroup$ Jun 9, 2020 at 6:50
  • $\begingroup$ @kglr is there any functional difference between your answer and mine? I wonder if I’m missing something. $\endgroup$
    – MarcoB
    Jun 9, 2020 at 14:04
  • $\begingroup$ @Marco, the only difference i can think of is the case f[]. (This is equivalent to f[x___] :=Map[p, {x}].) $\endgroup$
    – kglr
    Jun 9, 2020 at 19:13
1
$\begingroup$
Clear[f]
f[x__] := Map[p, {x}]

Then:

f[m, v, b]
(* Out: {p[{{1, 2}, {3, 4}}], p[{1, 2, 1}], p[10]} *)

If on the other hand, you really mean that m etc should appear as such, not evaluated, then that would require significant amounts of trickery. When such an abstruse requirement crops up, it sometimes makes me wonder whether the overall approach might not need reconsideration.

$\endgroup$
1
  • $\begingroup$ thank you for your input. You may be right about reconsidering this approach. $\endgroup$ Jun 9, 2020 at 6:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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