3
$\begingroup$

WRI provides the code below as a "neat example" of Fold. The code produces all of the subsets of {a, b, c}. As an exercise, I've been trying to replace the Function[ ..] with the ampersand form, but no luck yet. Thanks.

The original example:

Fold[Function[{s, e}, Join[s, Append[#, e] & /@ s]], {{}}, {a, b, c}]
$\endgroup$
  • 2
    $\begingroup$ In this case, you have to make a choice on which should be in "ampersand form", since the Append[] is dependent on both the inner and outer Function[] constructs. $\endgroup$ – J. M. is slightly pensive Sep 8 '17 at 16:24
  • 1
    $\begingroup$ Fold[Join[#, Function[x, Append[x, #2]] /@ #] &, {{}}, {a, b, c}]? $\endgroup$ – kglr Sep 8 '17 at 16:34
  • 1
    $\begingroup$ ...and kglr's comment gives the other "choice" I was talking about. $\endgroup$ – J. M. is slightly pensive Sep 8 '17 at 16:35
  • 1
    $\begingroup$ ... or Fold[Join[#, (x \[Function] Append[x, #2]) /@ #] &, {{}}, {a, b, c}] $\endgroup$ – kglr Sep 8 '17 at 16:36
  • $\begingroup$ Rabbit, I notice that you removed the Accept from my answer. May I know why? $\endgroup$ – Mr.Wizard Mar 2 '18 at 16:34
4
$\begingroup$

In this case you can use the operator form of Append, assuming version 10 or later:

Fold[Join[#, Append[#2] /@ #] &, {{}}, {a, b, c}]
{{}, {a}, {b}, {a, b}, {c}, {a, c}, {b, c}, {a, b, c}}
$\endgroup$
2
$\begingroup$
Fold[Join[#, Replace[#, x_List :> Join[x, {#2}], 1]] &, {{}}, {a, b, c}]

{{}, {a}, {b}, {a, b}, {c}, {a, c}, {b, c}, {a, b, c}}

Or

Fold[Join[#, Function[x, Append[x, #2]] /@ #] &, {{}}, {a, b, c}]

{{}, {a}, {b}, {a, b}, {c}, {a, c}, {b, c}, {a, b, c}}

Or

Fold[Join[#, (x \[Function] Append[x, #2]) /@ #] &, {{}}, {a, b, c}]

{{}, {a}, {b}, {a, b}, {c}, {a, c}, {b, c}, {a, b, c}}

$\endgroup$

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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