Search code examples
smlsmlnj

SMLNJ: Merging a repetitive case expression and matching part of a constructor name


I have 2 question regarding writing patterns for constructors:

  1. I want to merge two patterns of constructors into one, so I wouldn't have to write the same expression over and over again.
  2. I want to match a part of constructor with a pattern (I believe it's not possible but worth a shot)

A simplified example:

datatype X = A | CA | CB | D;
fun foo A = "A"
| foo CA = "A"
| foo CB = "A"
| foo _ = "else";

I would like to write a pattern something like this: A orelse C_ = "A" (preferably even to find a way to extract the value caught by the underscore).

Any help will be appreciated


Solution

  • SML/NJ supports so called or-patterns:

    datatype X = A | CA | CB | D
    
    fun foo (A | CA | CB) = "A"
      | foo _             = "else"
    

    That's the most you can do, though. There's no feature to partially match a datatype constructor name, i.e., your C_ syntax.