PLAI_Chapter2:Everything (We Will Say) About Parsing

Parsing is the act of turning an input character stream into a more structured, internal representation.

However, from our perspective parsing is mostly a distraction, because we want to study the parts of programming languages that are not
parsing.

Fortunately we will use s-expressions only in our parser, and our goal is to get away from parsing as quickly as possible! Indeed, if anything this should be inducement to get away even quicker.


#lang plai-typed

(define-type ArithC
  [numC (n : number)]
  [plusC (l : ArithC) (r : ArithC)]
  [multC (l : ArithC) (r : ArithC)])```

```lisp
(define (parse [s : s-expression]) : ArithC
  (cond
    [(s-exp-number? s) (numC (s-exp->number s))]
    [(s-exp-list? s)
     (let ([sl (s-exp->list s)])
       (case (s-exp->symbol (first sl))
         [(+) (plusC (parse (second sl)) (parse (third sl)))]
         [(*) (multC (parse (second sl)) (parse (third sl)))]
         [else (error 'parse "invalid list input")]))]
    [else (error 'parse "invalid input")]))```
```lisp
(parse '(+ (* 1 2) (+ 2 3)))```

---

你可能感兴趣的:(PLAI_Chapter2:Everything (We Will Say) About Parsing)