Search code examples
lispcommon-lispinfix-notation

Define function for evaluating infix expressions in Lisp


I am not very good in Lisp and I need to do a function which allows evaluating of infix expressions. For example: (+ 2 3) -> (infixFunc 2 + 3). I tried some variants, but none of them was successful.

One of them:

(defun calcPrefInf (a b c)
  (funcall b a c))

Solution

  • Assuming that you're using a lisp2 dialect, you need to make sure you're looking up the function you want to use in the function namespace (by using #'f of (function f). Otherwise it's being looked up in the variable namespace and cannot be used in funcall.

    So having the definition:

    (defun calcPrefInf (a b c)
        (funcall b a c))
    

    You can use it as:

    (calcPrefInf 2 #'+ 3)