Convert prefix expressions to infix expressions (lisp implementation)

It is relatively simple to convert a prefix expression to an infix expression.

Implementation code

The implementation function code is as follows:

;求得运算符号
(defun opsymbol(x)
	(cond
		((equal x 'setq) '=) ;给定的lisp函数。
		((equal x 'plus) '+)
		((equal x 'difference) '-)
		((equal x 'times) '*)
		((equal x 'quotient) '/)
		((equal x 'remainder) '\\)
		((equal x 'expt) '^)
		(t x)
	)
)

;前缀表达式转中缀表达式
(defun prefix_to_infix(L)
	(cond
		((null L) ())
		((atom L) L) ;简单情况。
		(t
			(list 	
				(prefix_to_infix (cadr L)) ;翻译第一部分
				(opsymbol (car L)) 			;查运算符号
				(prefix_to_infix (caddr L))	;翻译其余部分
			)
		)
	)
) 	

Add definition in portacle

Copy the code directly into the window. As shown below.

Program running effect

Enter the commands in turn

(prefix_to_infix '(times a b))

(prefix_to_infix '(TIMES PRINCIPAL (EXPT (PLUS 1.0 INTEREST) YEARS)))

(prefix_to_infix '(SETQ TOTAL (TIMES PRINCIPAL (EXPT (PLUS 1.0 INTEREST) YEARS))))

The result of the operation is as follows:

 

 

Guess you like

Origin blog.csdn.net/Alexabc3000/article/details/127350011