美文网首页
PLAI_Chapter3:A First Look at In

PLAI_Chapter3:A First Look at In

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

    Let’s write an evaluator, in the form of an interpreter, for our arithmetic language.

    数据类型和parser都和上一篇的一样,interp还是naive形态的。。。


    #lang plai-typed
    
    (define-type ArithC
      [numC (n : number)]
      [plusC (l : ArithC) (r : ArithC)]
      [multC (l : ArithC) (r : ArithC)])
    
    (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")]))
    
    (define (interp [a : ArithC]) : number
      (type-case ArithC a
        [numC (n) n]
        [plusC (l r) (+ (interp l) (interp r))]
        [multC (l r) (* (interp l) (interp r))]))
    
    (define (driver [s : s-expression]) : number  
      (interp (parse s)))
    
    (driver '(+ 1 1))
    

    相关文章

      网友评论

          本文标题:PLAI_Chapter3:A First Look at In

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