goadt

command
v0.0.0-...-0d2bfe8 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 23, 2024 License: Unlicense Imports: 7 Imported by: 0

Documentation

Overview

Parser and evaluator for a simple calculator with variables. The syntax is taken from http://eli.thegreenplace.net/2009/03/20/a-recursive-descent-parser-with-an-infix-expression-evaluator but simplified to have fewer levels of expressions.

EBNF:

<stmt> : <assign_stmt>

| <if_stmt>
| <cmp_expr>

<assign_stmt> : set <id> = <cmp_expr>

Note 'else' binds to the innermost 'if', like in C. Also, this is an integer language and we treat 0 as "false" and anything else as "true". The comparison expressions evaluate to 0 or 1, accordingly.

<if_stmt> : if <cmp_expr> then <stmt> [else <stmt>]

<cmp_expr> : <arith_expr> [== <arith_expr>]

| <arith_expr> [!= <arith_expr>]
| <arith_expr> [> <arith_expr>]
| <arith_expr> [< <arith_expr>]
| <arith_expr> [>= <arith_expr>]
| <arith_expr> [<= <arith_expr>]

<arith_expr> : <term> {+ <term>}

| <term> {- <term>}

<term> : <power> {* <power>}

| <power> {/ <power>}

<power> : <power> ** <factor>

| <factor>

<factor> : <id>

| <number>
| - <factor>
| ( <cmp_expr> )

<id> : [a-zA-Z_]\w+ <number> : \d+

Eli Bendersky [http://eli.thegreenplace.net] This code is in the public domain.

Same as tree.go, but adding a guard method on the Tree inteface to help type checking.

Eli Bendersky [http://eli.thegreenplace.net] This code is in the public domain.

Implementing the Tree ADT (Algebraic Data Type) example from https://en.wikipedia.org/wiki/Algebraic_data_type

The Haskell equivalent is:

data Tree = Empty

| Leaf Int
| Node Tree Tree

depth :: Tree -> Int depth Empty = 0 depth (Leaf n) = 1 depth (Node l r) = 1 + max (depth l) (depth r)

Eli Bendersky [http://eli.thegreenplace.net] This code is in the public domain.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL