3
$\begingroup$

I want to pass a list of pure variables to a function, in which the ordering of the variables matters. For instance, if I want a palindrome, my function might be:

func[{#1,#2,#2,#1}&]

I want to be able to generalise this to an arbitrary number of variables:

func[{#1,...,#n,...,#1}&]

So what I want is a simple way to write a function g[n] that calls func with n variables. How to achieve this? I've tried generating the list {#1,...,#n,...,#1}& with a Table, but it seems Mathematica is not interpreting the ampersand correctly.

$\endgroup$
4
$\begingroup$

Witness the following:

With[{n = 7}, 
     Function[Evaluate[ArrayPad[Slot /@ Range[n], {0, n - 1}, "Reflected"]]]]
       {#1, #2, #3, #4, #5, #6, #7, #6, #5, #4, #3, #2, #1} &

With[{n = 7}, 
     Function[Evaluate[ArrayPad[Slot /@ Range[n], {0, n}, "Reversed"]]]]
       {#1, #2, #3, #4, #5, #6, #7, #7, #6, #5, #4, #3, #2, #1} &
$\endgroup$
5
$\begingroup$

How about this:

g[n_]:=Function @@ {Slot /@ Join[#, Reverse[#]]&@Range[n]}

For a random order:

gr[n_] := Function @@ {Slot/@Array[RandomInteger[{1, n}] &, 2 n]}

All in all you can replace Range[n] with your own order of integers depending what you want to accomplice.

$\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.