1

I'm trying to teach myself some LISP and while I understand most of it, I have trouble grasping the eval function. I know that it does it for us already and that it's not good to use (so I hear), but how would I make a function that just adds?

So far I was attempting/thinking

(setf input-prompt "Enter addition epression: ")
(setf output-prompt "The value is: ")

(defun prompt-for-input (msg)
  (format t msg))


(defun sum (expression)
  (format t "Summing ~d and ~d.~%" x y)
  (+ x y))


(defun add ()
  (prompt-for-input input-prompt)
  (let ((expression (read)))
       ((sum (expression)))
  (add)))

Not really sure where to go on this, any help is appreciated.

1
  • What are you trying to do? It sounds like you want to call different functions based on the expression you read, without using eval. This is basically writing a small interpreter, which is something covered in most Lisp books (Little Schemer, etc.). But it would help if you could describe your problem more clearly. Commented Apr 15, 2013 at 23:34

1 Answer 1

2
(setf input-prompt "Enter addition expression: ")
(setf output-prompt "The value is: ")

(defun prompt-for-input (msg)
  (format t msg)
  (finish-output))

(defun sum (expression)
  (let ((x (second expression))
        (y (third expression)))
    (format t "~%Summing ~d and ~d.~%" x y)
    (+ x y)))

(defun add ()
  (prompt-for-input input-prompt)
  (sum (read)))

Run it:

CL-USER > (add)
Enter addition expression: (+ 1 2)
Summing 1 and 2.
3
Sign up to request clarification or add additional context in comments.

4 Comments

How does LISP go about figuring out what the 'second' and 'third' expression is?
(Second expression) is the second element of the list expression.
Your code doesn't compile, but I got the gist of it. So if I wanted to create other functions like sum and change 'add' to be a general expression holder, would I check which function to send it to with subseq?
@Nogg: why doesn't it compile? It compiles for me.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.