MathGroup Archive 1992

[Date Index] [Thread Index] [Author Index]

Search the Archive

more switching with lists

  • To: mathgroup at
  • Subject: more switching with lists
  • From: gaylord at
  • Date: Thu, 30 Jan 1992 05:00:26 -0600

in the previous episodes of this melodrama:
                                                                 the story

a call for help from a person in distress [stage center]:

Allen Hay of the UK sent in the following question:  
how do I eliminate the braces in  Switch[expr, {form1, val1, form2,
val2,form3, val3}] ?

the (modest) hero enters [stage left]:

I suggested using Switch[expr, {form1, val1, form2, val2, form3,
this works but it also produces the message Switch::argct: Switch called
with 2 arguments.
I suggested just turning the message off
Switch[expr, {form1, val1, form2, val2, form3, val3}]/.List->Sequence

a voice is heard from the wings [off-stage]:

one person (name lost, sorry) responded to my response as follows:
try Apply[Switch, Prepend[{form1, val1, form2, val2, form3, val3}, expr]]
which is based on M working from right to left.

the word comes down from on-high  [stage above]:

Jerry Keiper of WRI sent in the following response:
You don't need to turn off any messages.  Just don't evaluate it until
it has the right number of arguments:
In[1]:= Release[Hold[Switch[expr, {form1, val1, form2,
Out[1]= Switch[expr, form1, val1, form2, val2]
in this FINAL  installment, two more responses have come in: 

Chris (no last name, of MIT) suggests using pattern matching

Switch[expr, {a,b,c,d}]/.{x__}->x
Switch::argct: Switch called with 2 arguments.
Switch[expr, a, b, c, d]

(* note: this is basically the same as the previous Switch[expr,

Chris also proposes defining another function

switch[x_, {alist__}] := Switch[x, alist]

(* note:  if a new function switch is going to be introduced it should be
defined to replace Switch completely, as below *)

switch[expr, {alist__}] := Switch[expr, alist]
switch[expr, alist__] := Switch[expr, alist]

this brings to mind, a comment by Shawn Sheridan (of WRI) that M code could
be made more concise (and unreadable (like APL)) by creating new
user-defined functions based on M's built-in functions
pt[alist_List, n_Integer] := Partition [alist, n]

pt[{a, b, c, d, e, f}, 2]
{{a, b}, {c, d}, {e, f}}


from Tyler Perkin who 'just couldn't stand it anymore' and says he doesn't
know why Switch should be redefined and suggests the following as being the
elegant solution

Switch@@Join[{x}, thelist]

(*this is basically the same as the previous suggestion (rewritten now with
the suggested syntactic sugar)    Switch@@Prepend[{theList}, expr]  *)

there it is: 50 ways to skin a cat or 'leave your lover' (paul simon).. or

  • Prev by Date: Crashing Mma 2.0 on a Mac
  • Next by Date: About NonCommutativeMultiply
  • Previous by thread: Crashing Mma 2.0 on a Mac
  • Next by thread: About NonCommutativeMultiply