4
$\begingroup$

Suppose I have a list list with length L and a function listModifier[l_List, n_Integer, m_Integer] that returns a new list with length L. listModifier modifies the list in a way dependent on the parameters (n,m).

Furthermore, I possess another array A={{n3,m3},{n2,m2},{n1,m1}}, which contain information of the way list must be modified in three different steps.

What I am trying to do is something like

Apply[listModifier[#3, #1, #2] & , A] 

in order to construct the new array

A2={listModifier[#,n3,m3]&,listModifier[#,n2,m2]&,listModifier[#,n3,m3]&}

After which I expect Composition[A2] to yield single function that, when mapped upon the initial state list produces the final state of the list reached after the three consecutive modifications.

Unfortunately, it doesn't seem to work out as I can't seem to find a way to create the A2 array with pure functions.

$\endgroup$
5
$\begingroup$

If I understand you correctly then something like this might work for you.

A = {{A11, A12}, {A21, A22}, {A31, A32}}
A2 = Function[{l}, listModifier[l, #1, #2]] & @@@ A
A3 = Composition @@ A2
A3[{1, 2, 3}]

(* {{A11, A12}, {A21, A22}, {A31, A32}} *)

(* {Function[{l}, listModifier[l, A11, A12]], 
 Function[{l}, listModifier[l, A21, A22]], 
 Function[{l}, listModifier[l, A31, A32]]} *)

(* Function[{l}, listModifier[l, A11, A12]]@*
 Function[{l}, listModifier[l, A21, A22]]@*
 Function[{l}, listModifier[l, A31, A32]] *)

(* listModifier[
 listModifier[listModifier[{1, 2, 3}, A31, A32], A21, A22], A11, A12] *)

The trick was to use the Function construct as well as the normal slot mechanism (# /@) when building up A2.

Edit I always think better with concrete examples though, so here is one:

listModifier[l_List, n_Integer, m_Integer] := n/m + # & /@ l
A = RandomInteger[{1, 10}, {3, 2}]
A2 = Function[{l}, listModifier[l, #1, #2]] & @@@ A
A3 = Composition @@ A2
A3[{1, 2, 3}]

(* {{1, 4}, {2, 6}, {6, 8}} *)

(* {Function[{l}, listModifier[l, 1, 4]], 
 Function[{l}, listModifier[l, 2, 6]], 
 Function[{l}, listModifier[l, 6, 8]]} *)

(* Function[{l}, listModifier[l, 1, 4]]@*
 Function[{l}, listModifier[l, 2, 6]]@*
 Function[{l}, listModifier[l, 6, 8]] *)

(* {7/3, 10/3, 13/3} *)
$\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.