How do I do a SWITCH or SELECT CASE in NetLogo?

Viewed 303

NetLogo does not have a native SWITCH, SWITCH-CASE, or SELECT-CASE type of multiple condition, how do I do the same thing without having a giant mess of nested IF-ELSE statements?

2 Answers

Since NetLogo 6.1, NetLogo has supported multi-case ifelse, which can be used similarly to other languages' switch statements. Here is an example from the docs:

ask patches [
  let choice random 4
  (ifelse
    choice = 0 [
      set pcolor red
      set plabel "r"
    ]
    choice = 1 [
      set pcolor blue
      set plabel "b"
    ]
    choice = 2 [
      set pcolor green
      set plabel "g"
    ]
    ; elsecommands
    [
      set pcolor yellow
      set plabel "y"
  ])
]

And here is the example from the other answer rewritten to use it:

;; example of SWITCH style conditional block 
(ifelse 
  (criteria-1) [ action-1 ]
  (criteria-2) [ action-2 ]
  (criteria-3) [ action-3 ]
               [ default-action ]
) 

This does not need to have the "multi-close" of the ] on the last line, so it overall seems cleaner to me.

We can simulate a SWITCH statement with a chain of nested IF-ELSE statements, formatted so it's not a big mess, and actually easy to read and edit.

We will format the chain of IF-ELSE statement with the following goals:

  • avoid excessive indenting,
  • avoid overly long code lines
  • make it look more like switch in other languages
  • rearranging the cases does not break the syntax
  • there is a default case

A SWITCH Statement

Here's how it looks:

;; example of SWITCH style conditional block 
if-else [ criteria 1 ] [ action-1 ][
if-else [ criteria 2 ] [ action-2 ][
if-else [ criteria 3 ] [ action-3 ][
if-else [ true ]       [ default-action ][
]]]] 

Other considerations

Some programmers may find it offensive to have a default action that tests for true, and leaves the "else block" if the final "IF" empty. You can do what you like. I find making the default case explicit, makes all the actions formatted exactly the same, and avoids an awkward cluster of punctuation at the end.

  • Avoid overly long lines--it makes it harder to read
  • Keep conditions short--wrap them in reporter if needed.
  • Keep actions short--wrap them in procedures if needed.
  • This helps the code read more like a story and less like code.
Related