3
$\begingroup$

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.

$\endgroup$
  • 2
    $\begingroup$ Sequence @@ Which[# < 10, {#, 0}, # > 10, {0, #}] &? $\endgroup$ – kglr May 20 '15 at 15:33
  • $\begingroup$ Which[# < 10, Unevaluated@Sequence[#, 0], # > 10, Unevaluated@Sequence[0, #]] & I will leave it as a comment, I'm not good at explaining evaluation. $\endgroup$ – Kuba May 20 '15 at 15:34
  • $\begingroup$ Sequence takes a list, so your function is fine if you do Sequence[{#,0}]... $\endgroup$ – N.J.Evans May 20 '15 at 15:35
  • 1
    $\begingroup$ @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} $\endgroup$ – LLlAMnYP May 20 '15 at 15:58
  • 4
    $\begingroup$ 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? $\endgroup$ – Daniel Lichtblau May 20 '15 at 19:11
4
$\begingroup$
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]

| improve this answer | |
$\endgroup$
  • $\begingroup$ Just what I would have written myself. (Well f1 and f2 at least.) $\endgroup$ – Mr.Wizard May 20 '15 at 16:48

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.