Created
April 18, 2012 21:15
-
-
Save Thorium/2416610 to your computer and use it in GitHub Desktop.
Simple NumericLiteral example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(* | |
You can use numeric literals, constant expressions and operator overloading to make your own arithmetics. Useful in DSL languages. | |
With NumericLiterals, you can use any of Q, R, Z, I, N, G. | |
Basic syntax: [Number][Letter] will forward the call to the type NumericLiteral[Letter] to FromInt32 [Number] (or FromInt64 or FromString...) | |
*) | |
//----------------------------------------------------- | |
//First example: | |
module NumericLiteralN = | |
let FromZero() = "" | |
let FromOne() = "n" | |
let FromInt32 x = String.replicate x "n" | |
// Calls FromOne(): | |
let x1 = 1N | |
// val x1 : string = "n" | |
// Calls FromInt32(7): | |
let x2 = 7N | |
// val x1 : string = "nnnnnnn" | |
//Calls operator (+) on strings. | |
let x3 = 2N + 3N | |
// val x3 : string = "nnnnn" | |
//----------------------------------------------------- | |
//Second example: | |
type MyExpression = | |
| Const of int | |
| Plus of MyExpression * MyExpression | |
| Mult of MyExpression * MyExpression | |
with | |
static member (+) (x, y) = Plus(x,y) | |
static member (*) (x, y) = Mult(x,y) | |
module NumericLiteralZ = | |
let FromZero() = Const 0 | |
let FromOne() = Const 1 | |
let FromInt32 = Const | |
let rec eval tree = | |
match tree with | |
| Plus (x, y) -> eval x + eval y | |
| Mult (x, y) -> eval x * eval y | |
| Const x -> x | |
let expression = 3Z + (4Z * 5Z) | |
// val expression : MyExpression = Plus (Const 3,Mult (Const 4,Const 5)) | |
let res = eval expression | |
// val res : int = 23 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment