3

For example if the input is x and x<10 the output is Sequence[x,0],if x>10 the output is Sequence[0,x] but obviously

Which[#<10,Sequence[#,0],#>10,Sequence[0,#]]&

does not work. How to solve this problem? Thank you!


but I find

Piecewise[{{Sequence[#, 0], # < 10}, {Sequence[0, #], # > 10}}] &

is worked minutes age why?. I feel very confused.

Mr.Wizard
  • 271,378
  • 34
  • 587
  • 1,371
zzy
  • 319
  • 1
  • 6
  • 2
    Sequence @@ Which[# < 10, {#, 0}, # > 10, {0, #}] &? – kglr May 20 '15 at 15:33
  • Which[# < 10, Unevaluated@Sequence[#, 0], # > 10, Unevaluated@Sequence[0, #]] & I will leave it as a comment, I'm not good at explaining evaluation. – Kuba May 20 '15 at 15:34
  • Sequence takes a list, so your function is fine if you do Sequence[{#,0}]... – N.J.Evans May 20 '15 at 15:35
  • 1
    @N.J.Evans and it will subsequently return a list. In other words, {a, Sequence[{b,c}], d} evaluates to {a,{b,c},d}, not {a,b,c,d} – LLlAMnYP May 20 '15 at 15:58
  • Oops, you're right. I was focused on the fact that the original version returned an error and didn't even pay attention to that. @kguler and Kuba got it though. – N.J.Evans May 20 '15 at 16:28
  • Closely related: (3700) -- my answer there explains the situation in some detail, though each method will need minor adaptation. – Mr.Wizard May 20 '15 at 16:48
  • 4
    Sequence is not a function to use lightly, particularly as the head of a result. Is there some compelling case for using it here in preference to, say, List? – Daniel Lichtblau May 20 '15 at 19:11

1 Answers1

4
f1 = Which[# < 10, ## &[#, 0], # > 10, ## &[0, #]] &;
f2 = ## & @@ Which[# < 10, {#, 0}, # > 10, {0, #}] &;
f3 = ## & @@ {Append, Prepend}[[1 + Boole[# > 10]]][{#}, 0] &;
f4 = ## & @@ {Identity, Reverse}[[1 + Boole[# > 10]]][{#, 0}] &;
f5 = Which[# < 10, {#, 0}, # > 10, {0, #}] /. List -> Sequence &;

f1 @ 1

Sequence[1, 0]

f1 @ 11

Sequence[0,11]

f2 @ 1

Sequence[1, 0]

f2 @ 11

Sequence[0,11]

f3 @ 1

Sequence[1, 0]

f3 @ 11

Sequence[0,11]

kglr
  • 394,356
  • 18
  • 477
  • 896