24 people like it.

Small embedded DSL to write in F# "Who is John Galt?"

This snippet how we can use F# constructs like discrimated unions, functions and symbolic identifiers to represent proper language statements (albeit limited) using valid F# code.

 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
12: 
13: 
14: 
15: 
16: 
17: 
18: 
19: 
20: 
21: 
22: 
23: 
//Discriminated unions to represents the elements of a tense.
type Name = | John | Galt
type Verb = | Is | Was
type Mark = QuestionMark | ExclamationMark

//We must use symbolic identifiers to represent Marks since union cases must
//be uppercase identifiers. They are not function values!
let (?) = QuestionMark
let (!) = ExclamationMark

//A function to represent a tense.
//Please note that we must use QuestionMark instead of (?) in the pattern matching
//because identifiers in pattern matching are mean to capture values, then when using (?)
//it will behave like _
let Who a b c d = 
    match a,b,c,d with
    | Is, John, Galt, QuestionMark | Was, John, Galt, QuestionMark 
        -> "John Galt is a fictional character in Ayn Rand's novel Atlas Shrugged."
    | Is,_,_,_ | Was,_,_,_ 
        -> "I will suggest you to Google or Bing that name."

//The famous query, now a valid F# expression
Who Is John Galt (?)
union case Name.John: Name
union case Name.Galt: Name
type Verb =
  | Is
  | Was

Full name: Script.Verb
union case Verb.Is: Verb
union case Verb.Was: Verb
type Mark =
  | QuestionMark
  | ExclamationMark

Full name: Script.Mark
union case Mark.QuestionMark: Mark
union case Mark.ExclamationMark: Mark
val Who : a:Verb -> b:Name -> c:Name -> d:Mark -> string

Full name: Script.Who
val a : Verb
val b : Name
val c : Name
val d : Mark
Raw view Test code New version

More information

Link:http://fssnip.net/33
Posted:13 years ago
Author:Horacio Nuñez
Tags: dsl , embedded