Skip to content

Commit

Permalink
Update ArithmeticExpressions.fir
Browse files Browse the repository at this point in the history
  • Loading branch information
osa1 committed Jan 18, 2025
1 parent 5f3d226 commit ea004ec
Showing 1 changed file with 9 additions and 9 deletions.
18 changes: 9 additions & 9 deletions ArithmeticExpressions.fir
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# An implementation of the "Untyped Arithmetic Expressions" language described in Types and
# Programming Languages section 3.

fn main(pgm: Str) = printStr(eval(parse(pgm)).toStr())
main(pgm: Str) = printStr(eval(parse(pgm)).toStr())

type Term:
True
Expand All @@ -25,7 +25,7 @@ type Value:
Bool(Bool)
Num(I32)

fn eval(term: Term): Value =
eval(term: Term): Value
match term:
Term.True: Value.Bool(Bool.True)

Expand Down Expand Up @@ -60,24 +60,24 @@ fn eval(term: Term): Value =
Value.Num(value): Value.Bool(value == 0)

impl Value:
fn toStr(self): Str =
toStr(self): Str
match self:
Value.Bool(value): value.toStr()
Value.Num(value): value.toStr()

fn parse(pgm: Str): Term =
parse(pgm: Str): Term
let (term = term, rest = rest) = parseWithRest(pgm)
if !rest.isEmpty():
panic("Leftover code after parsing the program: \"`rest`\"")
term

fn skipWhitespace(pgm: Str): Str =
skipWhitespace(pgm: Str): Str
while pgm.len() > 0 && pgm.startsWith(" "):
pgm = pgm.substr(1, pgm.len())
pgm

## Parse the program, return the parsed term and the unparsed part of the program.
fn parseWithRest(pgm: Str): (term: Term, rest: Str) =
parseWithRest(pgm: Str): (term: Term, rest: Str)
match skipWhitespace(pgm):
"0" rest:
(term = Term.Zero, rest = rest)
Expand All @@ -104,7 +104,7 @@ fn parseWithRest(pgm: Str): (term: Term, rest: Str) =
_:
panic("Invalid syntax: \"`pgm`\"")

fn parseArg(pgm: Str): (arg: Term, rest: Str) =
parseArg(pgm: Str): (arg: Term, rest: Str)
# Skip "("
if pgm.isEmpty():
panic("Unexpected end of program while parsing arguments")
Expand All @@ -128,13 +128,13 @@ fn parseArg(pgm: Str): (arg: Term, rest: Str) =

(arg = arg, rest = rest)

fn expectKeyword(pgm: Str, kw: Str): Str =
expectKeyword(pgm: Str, kw: Str): Str
let pgm = skipWhitespace(pgm)
if !pgm.startsWith(kw.toStr()):
panic("Expected \"`kw`\", found \"`pgm`\"")
pgm.substr(kw.len(), pgm.len())

fn testMain() =
testMain(): {} ()
main("0")
main("succ(0)")
main("succ(succ(0))")
Expand Down

0 comments on commit ea004ec

Please sign in to comment.