cakeml icon indicating copy to clipboard operation
cakeml copied to clipboard

Support for multi-case functions defined by pattern matching

Open xrchz opened this issue 8 years ago • 8 comments

Function declarations currently only accept variables as arguments, but in SML one can do pattern matching with a declaration. CakeML AST does not support that, but the parser could generate the corresponding case expression on the tuple of argument variables. Or the AST could be augmented, if necessary, to do something more sophisticated.

xrchz avatar Apr 23 '17 07:04 xrchz

Functions, the fn form and val all allow patterns already. See for example the tests in compiler/parsing/tests/cmlTestsScript.sml around line 192. Not to mention the grammar itself.

mn200 avatar Apr 24 '17 00:04 mn200

@tanyongkiam Can you clarify what you meant by function definitions with patterns not working?

xrchz avatar Apr 24 '17 00:04 xrchz

Hmm, something like

fun f [] = [] | f (x::xs) = x;

doesn't parse for me

tanyongkiam avatar Apr 24 '17 00:04 tanyongkiam

Ah. That's true. The syntax only allows for patterns; it doesn't allow for multiple cases separated by bars (except in the case syntax of course). I think something like

fun f [] _ = 3
   | f (x::xs) 2 = 1 + x
   | f _ _ = 0

would have to parsed into

fun f gv1 gv2 = 
   case (gv1, gv2) of 
       ([], _) => 3
   |  (x::xs, 2) => 1 + x
   | (_, _) => 0

Would this then cause the (unnecessary) allocation of the tuple?

mn200 avatar Apr 24 '17 00:04 mn200

Yes, it would allocate the tuple. To avoid this, I think the AST (and compiler) would need to support this syntax. @sowens do you have any thoughts?

xrchz avatar Apr 24 '17 00:04 xrchz

From video meeting: There are three strategies: full syntactic sugar (the parser does all the work), add an AST entry for it but desugar it early in the compiler, or carry it all the way to patLang and compile it away without allocating the tuple. @SOwens prefers the middle one.

(However, the whole thing is high cost low benefit… similar to records, which might have a better ratio. So maybe we better spend our time on records...)

xrchz avatar Apr 25 '17 12:04 xrchz

I'm happy to do the parser part of all three strategies (the changes will all be pretty similar).

mn200 avatar Apr 27 '17 09:04 mn200

Do we still know if a tuple is allocated or it's optimized away?

ordinarymath avatar Sep 11 '25 05:09 ordinarymath