zoukankan      html  css  js  c++  java
  • PLAI那些事01 AE

    AE : Concrete syntax

    <AE> ::= <num>
           | {+ <AE> <AE>}
           | {- <AE> <AE>}
    

    AE : Abstract syntax

    (define-type AE
      [num (n number?)]
      [add (lhs AE?)
           (rhs AE?)]
      [sub (lhs AE?)
           (rhs AE?)])
    

    parse : sexp -> AE

    (define (parse sexp)
      (cond 
        [(number? sexp) (num sexp)] 
        [(list? sexp) 
         (case (first sexp) 
           [(+) (add (parse (second sexp)) 
                     (parse (third sexp)))] 
           [(-) (sub (parse (second sexp)) 
                     (parse (third sexp)))])]))
    
    (define (parse sexp)
      (cond 
        [(number? sexp) (num sexp)] 
        [(and (= 3 (length sexp)) 
              (eq? (first sexp) ’+)) 
         (add (parse (second sexp))
              (parse (third sexp)))] 
        [(and (= 3 (length sexp)) 
              (eq? (first sexp) ’-)) 
         (sub (parse (second sexp))
              (parse (third sexp)))] 
        [else (error ’parse "bad syntax: ~a" sexp)]))
    
    (define (parse sexp)
      (cond
        [(number? sexp) (num sexp)]
        [(and (= 3 (length sexp)) (eq? (first sexp) '+))
         (add (parse (second sexp)) (parse (third sexp)))]
        [(and (= 3 (length sexp)) (eq? (first sexp) '-))
         (sub (parse (second sexp)) (parse (third sexp)))]
        [else (error 'parse "bad syntax: ~a" sexp)]))
    
    (define (parse sexp)
      (match sexp
        [(? number?) (num sexp)]
        [(list '+ l r) (add (parse l) (parse r))]
        [(list '- l r) (sub (parse l) (parse r))]
        [else (error 'parse "bad syntax: ~a" sexp)]))
    

    interp : AE -> number

    (define (interp ae)
      (type-case AE ae
        [num (n) n]
        [add (l r) (+ (interp l) (interp r))]
        [sub (l r) (- (interp l) (interp r))]))
    
  • 相关阅读:
    PY个树状数组
    PY 个板子计划【雾
    PY个欧拉筛
    【NOI2007】项链工厂 ——老题新做.jpg
    Min-Max 容斥的证明
    51nod 1963 树上Nim
    ●BZOJ 3566 [SHOI2014]概率充电器
    ●BZOJ 3640 JC的小苹果
    ●BZOJ 1444 [Jsoi2009]有趣的游戏
    ●Joyoi Dotp 驱逐猪猡
  • 原文地址:https://www.cnblogs.com/lastk/p/12832532.html
Copyright © 2011-2022 走看看