我定义了一个名为msl
#lang plai-typed
(define-type msl
[msl-num (n : number)]
[msl-add (l : msl) (r : msl)]
[msl-mul (l : msl) (r : msl)]
[msl-sub (l : msl) (r : msl)]
[msl-pow (l : msl) (r : msl)]
[msl-error (s : string)]
)
(define(** u t)
(cond
((= u 1) t)
(else
(* t(**(sub1 u) t)))))
我有一个解析器函数,可将s-expression
转换为msl
(define (parse [s : s-expression]) : msl
(cond
[(s-exp-number? s) (msl-num (s-exp->number s))]
[(s-exp-list? s)
(let ([sl (s-exp->list s)])
(case (s-exp->symbol (first sl))
[(+) (msl-add (parse (second sl)) (parse (third sl)))]
[(*) (msl-mul (parse (second sl)) (parse (third sl)))]
[ (-) (msl-sub (parse (second sl)) (parse (third sl)))]
[ (**) (msl-pow (parse (second sl)) (parse (third sl))) ]
[else (error 'parse "invalid list input")]))]
[else (error 'parse "invalid input")]))
我的问题是:如何将msl
表达式转换为s-expression
?我是这个主题的初学者
答案 0 :(得分:0)
你绝对可以这样做。
在我回答这个问题之前,虽然...... 为什么你想这样做?为了实现评估者,通常不需要这样做。
据说:这很简单。我将从编写一些测试用例开始:
(test (unparse (msl-add (msl-num 3) (msl-num 4))) '(+ 3 4))
......以及代码本身
;; convert an msl to an s-expression:
(define (unparse parsed)
(type-case msl parsed
[msl-num (n) ...]
...))
......等等。如果这没有意义,请告诉我。