stanza

How to write a fall-through switch statement in Stanza?


I'm writing a switch statement in Stanza and some of my cases are the same. I'd like to minimize code repetition. How can I merge cases together?

val a = randomSmallInteger()
switch(a) :
  0 : println("zero")
  1 : println("one")
  2 : println("two or three")
  3 : println("two or three")

I imagine it would look like

switch(a) :
  0 : println("zero")
  1 : println("one")
  2,3 : println("two or three")

Solution

  • Stanza does not support a fall-through behavior for its switch statement. The following is not very idiomatic (I would recommend a simple if-else chain instead) but it looks very similar to your code. It uses the general form of the switch statement where a closure is used for the predicate.

    switch contains?{_, a} :
      [0] : println("zero")
      [1] : println("one")
      [2, 3] : println("two or three")
    

    Patrick