Files
cs5/05-parsing/main.rkt
T
2025-10-10 14:00:16 -04:00

107 lines
1.7 KiB
Racket

#lang pl
(define-type AE
[R1 Prod AE]
[R2 Prod])
(define-type Prod
[R3 Atom Prod]
[R4 Atom])
(define-type Atom
[R5 Number]
[R6 AE])
; Symbols:
; 'sum
; 'mul
; 'groups
; 'groupe
; parse-ae: s: Sexpr → AE
(: parse-ae : (Sexpr -> AE))
; Parse a Sexpr.
(define (parse-ae s)
; parseae: s: Sexpr, a: Sexpr → AE
(: parseae : (Sexpr Sexpr -> AE))
; Parse a Sexpr and while accumulating in a.
(define (parseae s a)
(match s
[(list prod ae) (parseae/group (rest s) '())]
[(cons (number: n) r) (R2 (R4 (R5 n)))]))
(parseae s '()))
(test (parse-ae '(3)) => (R2 (R4 (R5 3))))
(test (parse-ae '(groups 3 groupe)) => (R2 (R4 (R6 (R2 (R4 (R5 3)))))))
(test (parse-ae '(1 plus 1)) => (R1 (R4 (R5 1)) (R2 (R4 (R5 1)))))
; parse-ae/h: s: Sexpr, ae: AE → AE
#|
<AE> ::= <PROD> + <AE> (1)
| <PROD> (2)
<PROD> ::= <ATOM> * <PROD> (3)
| <ATOM> (4)
<ATOM> ::= <num> (5)
| { <AE> } (6)
"5"
<atom> (5)
<num> 5
"{5}"
<atom> (6)
<ae> (2)
<prod> (4)
<atom> (5)
<num> 5
"{2 + 5}"
<atom> (6)
<ae> (1)
<prod> (4)
<atom> (5)
<num> 2
<ae> (2)
<prod> (4)
<atom> (5)
<num> 5
"{{{2 + 5}} * {5 * {{3 + 6}}}}"
<atom> (6)
<ae> (2)
<prod> (3)
<atom> (6)
<atom> (6)
<ae> (1)
<prod> (4)
<atom> (5)
<num> 2
<ae> (2)
<prod> (4)
<atom> (5)
<num> 5
<prod> (4)
<atom> (6)
<prod> (3)
<atom> (5)
<num> 5
<prod> (4)
<atom> (6)
<atom> (6)
<ae> (1)
<prod> (4)
<atom> (5)
<num> 3
<ae> (2)
<prod> (4)
<atom> (5)
<num> 6
|#