Is possible to use F# pattern matching as a solver/library for another language or DSL?

416 Views Asked by At

I'm building a toy language, I want to have pattern matching. I could build the whole thing itself (and don't know how) but because I will do it in F# I wonder if I can defer the whole thing to it.

So, I have a interpreter and my custom syntax. If I give a AST, is possible to use F# use it to solve the pattern matching?

Another way to look at this, is possible to use F# pattern matching from C# and other .NET languages?

For example, if the program is (in invented syntax almost like F#):

case x with 
    ( 1 , 2 , Three):
        print("Found 1, 2, or 3!")
    else var1:
        print("%d" % var1)

Is possible to do

matched, error = F#MagicHere.Match(EvaluateMyAST)
1

There are 1 best solutions below

2
On

I'm not exactly sure if I understand your question correctly, but I suspect you could use F# Compiler Service to do what you need. Basically, the compiler service lets you call some of the tasks that the compiler performs (and it is a normal .NET library).

The first step would be to turn your AST into valid F# code - I guess you could find a systematic way of doing this (but it requires some thinking). Then you can use F.C.S to:

  • Type-check the expression, which gives you warnings for overlapping cases and missing cases (e.g. when you have an incomplete pattern match).

  • It gives you the AST of the pattern matching and I believe you can even get a decision tree that you can interpret to evaluate the pattern matching.

  • Alternatively, you could use F.C.S to compile the code and run it (provided that you can translate your DSL to F# code)