;;; prefix2postfix.lsp ;;; An example Lisp program for CSE 341. ;;; S. Tanimoto, June, 2003. (setq e1 '(+ 3 (* 4 5))) (defun flatten (expr) "Make a 1-level list out of the given expression." (cond ((null expr) nil) ((atom expr) (list expr)) ((append (flatten (car expr)) (flatten (cdr expr)) ) )) ) (defun prefix2postfix (expr) "Convert an expression from Lisp parenthesized prefix form to unparenthesized postfix." (cond ((atom expr) expr) (t (flatten (append (mapcar #'prefix2postfix (cdr expr)) (list (car expr)) ) )) ) ) (defun insert-separators (lst sep) "Prevent consecutive numbers by inserting SEP where needed." (cond ((null lst) nil) ((null (cdr lst)) lst) ((and (numberp (car lst))(numberp (cadr lst))) (cons (car lst) (cons sep (insert-separators (cdr lst) sep))) ) (t lst) ) ) (defun list2string (lst sepsym sepstring) "Output a list as a string, converting any instance of symbol SEPSYM to the string SEPSTRING." (cond ((eq lst sepsym) sepstring) ((atom lst)(format nil "~A" lst)) (t (apply #'concatenate (cons 'string (mapcar #'(lambda (x) (list2string x sepsym sepstring)) lst) ) )) ) ) (defun test () "Show various stages of transforming an example expression." (let* ((post-e1 (prefix2postfix e1)) (sepsym 'sep) (sepstring ",") (post-e1-with-sep (insert-separators post-e1 sepsym)) (result (list2string post-e1-with-sep sepsym sepstring)) ) (format t "~A~%" e1) (format t "~A~%" post-e1) (format t "~A~%" post-e1-with-sep) (format t "~A~%" result) ) )