koka-lang / koka

Koka language compiler and interpreter
http://koka-lang.org
Other
3.16k stars 151 forks source link

Extensible Matching via Implicits #529

Open TimWhiting opened 1 month ago

TimWhiting commented 1 month ago

It might be occasionally useful to extend the matching of Koka. Specifically I'm thinking about for slices. There is no need to convert the slice to a string to see if a slice matches a string, but currently that is what you need to do.

Instead it would be nice to do something like:

slice/match someSlice
  "" -> "empty"
  "hello" -> "world!"

Where slice match is defined as

pub extern slice/match(sl: sslice, s: string): bool
   ... Extern code to match a slice to a string

It basically would desugar to a sequence of if/elif, with else for a catch-all, just like the current match & since the pattern language doesn't change it still allows for exhaustiveness checking.

Of course this might be tricky when dealing with nested patterns (such as when one of your constructors contains a slice). Maybe instead of explicitly calling slice/match Koka just looks up a match function with the appropriate arguments:

match listofslice
  Cons("hello", Cons("world")) -> "Hi!"
  _ -> "Whatever"

In this case the match desugars to:

if listofslice.is-cons && slice/match(listofslice.head, "hello") && 
      listofslice.tail.is-cons &&  slice/match(listofslice.tail.head, "world") then 
  "Hi" 
else "Whatever"

And exhaustiveness checking still does not need to change.