Search code examples
smlsmlnj

Multiple Patterns in 1 case


In SML, is it possible for you to have multiple patterns in one case statement?

For example, I have 4 arithmetic operators express in string, "+", "-", "*", "/" and I want to print "PLUS MINUS" of it is "+" or "-" and "MULT DIV" if it is "*" or "/".

TL;DR: Is there somewhere I can simplify the following to use less cases?

case str of
   "+" => print("PLUS MINUS")
 | "-" => print("PLUS MINUS")
 | "*" => print("MULT DIV")
 | "/" => print("MULT DIV")

Solution

  • Given that you've tagged your question with the tag, then yes, SML/NJ supports this kind of patterns. They call it or-patterns and it looks like this:

    case str of
      ("+" | "-") => print "PLUS MINUS"
    | ("*" | "/") => print "MULT DIV"
    

    Notice the parentheses.

    The master branch of MLton supports it too, as part of their Successor ML effort, but you'll have to compile MLton yourself.

    val str = "+"
    
    val _ =
      case str of
        "+" | "-" => print "PLUS MINUS"
      | "*" | "/" => print "MULT DIV"
    

    Note that MLton does not require parantheses. Now compile it using this command (unlike SML/NJ, you have to enable this feature explicitly in MLton):

    mlton -default-ann 'allowOrPats true' or-patterns.sml