Note that there are some explanatory texts on larger screens.

plurals
  1. POF# design pattern
    text
    copied!<p>Lets say I'm building a parser for a domain-specific language in F#.</p> <p>I've defined a discriminated union to represent expressions:</p> <pre><code> type Expression = | Equality of Expression*Expression | NonEquality of Expression*Expression | Or of Expression*Expression | And of Expression*Expression | If of Expression*Expression | IfElse of Expression*Expression*Expression | Bool of bool | Variable of string | StringLiteral of string </code></pre> <p>Now, I've built up an AST of type <code>Expression</code> and want to generate code for it. I have one function which does type inference and type checking on an expression.</p> <p>It's defined like</p> <pre><code> let rec InferType expr = match expr with | Equality(e1,e2) -&gt; CheckTypes (InferType e1) (InferType e2) | Or(e1,e2) -&gt; CheckTypes (InferType e1) (InferType e2) | And(e1,e2) -&gt; CheckTypes (InferType e1) (InferType e2) ... </code></pre> <p>And I have another function to generate code which follows a similar pattern: Take an expression, write pattern-matching statements for each item in the union.</p> <p>My question is: Is this the idiomatic way to do it in F#?</p> <p>It seems to me that it would be cleaner if each member of the union defined its own <code>InferType</code> and <code>GenerateCode</code> locally with it.</p> <p>If I were using C#, I would define some abstract base class called <code>Expression</code> with virtual methods for <code>InferType</code> and <code>GenerateCode</code> and then override them in each subclass.</p> <p>Is there any other way to do this?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload