美文网首页
PLAI_Chapter2:Everything (We Wil

PLAI_Chapter2:Everything (We Wil

作者: thehgz | 来源:发表于2015-11-12 12:33 被阅读39次

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 Wil

      本文链接:https://www.haomeiwen.com/subject/hdihhttx.html