Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

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.

share|improve this question
add comment

2 Answers

up vote 4 down vote accepted

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} &
share|improve this answer
add comment

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.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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