Data commit

This commit is contained in:
Ingy döt Net 2023-07-01 11:58:00 -04:00
parent 7387c8f97b
commit cb5bb5e222
199093 changed files with 3378972 additions and 0 deletions

View file

@ -0,0 +1,8 @@
module AbstractSyntaxTree
type Expression =
| Int of int
| Plus of Expression * Expression
| Minus of Expression * Expression
| Times of Expression * Expression
| Divide of Expression * Expression

View file

@ -0,0 +1,24 @@
{
module Lexer
open Parser // we need the terminal tokens from the Parser
let lexeme = Lexing.LexBuffer<_>.LexemeString
}
let intNum = '-'? ['0'-'9']+
let whitespace = ' ' | '\t'
let newline = '\n' | '\r' '\n'
rule token = parse
| intNum { INT (lexeme lexbuf |> int) }
| '+' { PLUS }
| '-' { MINUS }
| '*' { TIMES }
| '/' { DIVIDE }
| '(' { LPAREN }
| ')' { RPAREN }
| whitespace { token lexbuf }
| newline { lexbuf.EndPos <- lexbuf.EndPos.NextLine; token lexbuf }
| eof { EOF }
| _ { failwithf "unrecognized input: '%s'" <| lexeme lexbuf }

View file

@ -0,0 +1,26 @@
%{
open AbstractSyntaxTree
%}
%start Expr
// terminal tokens
%token <int> INT
%token PLUS MINUS TIMES DIVIDE LPAREN RPAREN
%token EOF
// associativity and precedences
%left PLUS MINUS
%left TIMES DIVIDE
// return type of Expr
%type <Expression> Expr
%%
Expr: INT { Int $1 }
| Expr PLUS Expr { Plus ($1, $3) }
| Expr MINUS Expr { Minus ($1, $3) }
| Expr TIMES Expr { Times ($1, $3) }
| Expr DIVIDE Expr { Divide ($1, $3) }
| LPAREN Expr RPAREN { $2 }

View file

@ -0,0 +1,21 @@
open AbstractSyntaxTree
open Lexer
open Parser
let parse txt =
txt
|> Lexing.LexBuffer<_>.FromString
|> Parser.Expr Lexer.token
let rec eval = function
| Int i -> i
| Plus (a,b) -> eval a + eval b
| Minus (a,b) -> eval a - eval b
| Times (a,b) -> eval a * eval b
| Divide (a,b) -> eval a / eval b
do
"((11+15)*15)*2-(3)*4*1"
|> parse
|> eval
|> printfn "%d"