5
$\begingroup$

I have a list which has the number of n.

list={x1,x2,x3,x4,x5,...xn}

when I use these elements as arguments of a function f[x], I want to express function with iteration which is similar to NestList. According to the value of n, the arguments of the function are determined by the rule below.

enter image description here

Any ideas for this? Thanks.

$\endgroup$
1
  • $\begingroup$ If the list has length n where do the other arguments come from? For example, if n = 2 the list is {x1, x2} but you say that f should be f(x1, x2, x3). Where does x3 come from? $\endgroup$
    – Bob Hanlon
    Commented Oct 19, 2017 at 15:04

4 Answers 4

4
$\begingroup$
ClearAll[fold1, folds2, fold3, fold4]

fold1  = List @@ Partition[# @@ #2, Length@#2, 2, -1, {}] &;

fold2[f_, l_] := f[## & @@ l[[;; #]]] & /@ Range[1, Length@l, 2]

fold3 = Extract[#2, List /@ Range[Range[1, Length@#2, 2]], Function[k, # @@ k]] &;

fold4 = # @@@ Extract[#2, List /@ Range[Range[1, Length @ #2, 2]]]&;

Examples:

fold1[f, {x1, x2, x3, x4, x5}]

{f[x1], f[x1, x2, x3], f[x1, x2, x3, x4, x5]}

fold1[f, {x1, x2, x3, x4, x5, x6, x7}]

{f[x1], f[x1, x2, x3], f[x1, x2, x3, x4, x5], f[x1, x2, x3, x4, x5, x6, x7]}

(fold1[f, #] ==  fold2[f, #] == fold3[f, #] == fold4[f, #])&[{x1, x2, x3, x4, x5, x6, x7}]

True

$\endgroup$
5
$\begingroup$

Another one:

list = {x1, x2, x3, x4, x5};
f @@@ FoldList[Flatten@*List, list[[{1}]], Rest@list][[;; ;; 2]]

And another:

Block[{f}
, SetAttributes[f, Flat]
; FoldList[f, f /@ list][[;; ;; 2]]
]
{f[x1], f[x1, x2, x3], f[x1, x2, x3, x4, x5]}
$\endgroup$
4
$\begingroup$

my original answer was unnecessarily complicated. A Table command is all what is needed

k = 4;(*must be <= 2*n-1 where n is length of list below*)
list = {x1, x2, x3, x4, x5, x6, x7};
Clear[f]
Flatten@Table[f[Sequence @@ list[[1 ;; (2 i - 1)]]], {i, Range[k]}]

Mathematica graphics

Original

k = 4; (*must be <= 2*n-1 where n is length of list below*)
list = {x1, x2, x3, x4, x5, x6, x7};
Clear[f]
Flatten@MapIndexed[ {z = First[#2];
    f[Sequence @@ list[[1 ;; (2 z - 1)]]]} &, Range[k]]

Mathematica graphics

$\endgroup$
4
$\begingroup$

Here we just need to specify n. The list of variables is built by Array, and then the mapping # generates the arguments of f. The List->Sequence removes extra brackets { } that would otherwise appear in the argument of f.

n = 4;
list = Array[x, 2 n - 1]; 
(f[list[[1 ;; 2 # - 1]]] /. List -> Sequence) & /@ Range[n]

{f[x[1]], f[x[1], x[2], x[3]], f[x[1], x[2], x[3], x[4], x[5]], 
     f[x[1], x[2], x[3], x[4], x[5], x[6], x[7]]}
$\endgroup$

Your Answer

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

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