Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested case statements in SML

This is more of a stylistic question than anything else. Given the following piece of code:

case e1 of                    (* datatype type_of_e1  = p1 | p2 *)
    p1 => case e11 of         (* datatype type_of_e11 = NONE | SOME int *)
              NONE => expr11
            | SOME v => expr12 v
  | p2 => case e21 of         (* datatype type_of_e21 = NONE | SOME string *)
              NONE => expr21
            | SOME v => expr22 v

Is there a way to resolve the types of rules don't agree error caused by trying to pattern match e11 to p2, other than enclosing p1's expression in parenthesis? The p2 pattern has another case statement, to avoid the 'just switch the patterns' answer ;-).

update: changed the code to reflect a more concrete case

like image 657
slash3r Avatar asked Feb 05 '13 13:02

slash3r


3 Answers

The answer is "(" and ")". My example:

case e1 of                   
   p1 => ( case e11 of         
              NONE => expr11
              | SOME v => expr12 v )
   | p2 => ( case e21 of         
                NONE => expr21
                | SOME v => expr22 v )

This really works! Cool :) You can try it too.

like image 83
Beraliv Avatar answered Nov 20 '22 04:11

Beraliv


No. The syntactic rules in the Definition of Standard ML state that the match arms of a case expression attempt to maximally consume potential clauses. And since there's no "end case" or similar marker in the language, the parser will merrily eat each of the "| pat => exp" clauses that you feed it until it sees something that terminates a list of match clauses.

like image 35
Lars Bergstrom Avatar answered Nov 20 '22 03:11

Lars Bergstrom


Plain and short answer: no. But what's wrong with parentheses?

(Of course, you can also bracket in other ways, e.g. with a 'let', or by factoring into auxiliary functions, but parentheses are the canonical solution.)

like image 4
Andreas Rossberg Avatar answered Nov 20 '22 02:11

Andreas Rossberg