views:

50

answers:

2

Hi! I need to translate some code from Scheme to Common Lisp. Now, I have something like this:

(defun sum (term a next b)
  (if (> a b)
    0
    (+ (term a) (sum term (next a) b))))

(defun sum-int (a b)
  (defun (ident x) x)
  (sum ident a 1+ b))

but it produces errors.

* - DEFUN: the name of a function must be a symbol, not (IDENT X)

Help me plese. Thanks

upd original code:

(define (sum term a next b)
  (if (> a b)
    0
    (+ (term a) (sum term (next a) b))))

(define (sum-int a b)
  (defun (identity x) x)
  (define identity a 1+ b))
+1  A: 

I think I got the gist of what you were looking for...

(defun sum (term a next b)
  (if (> a b)
      0
      (+ (funcall term a) (sum term (funcall next a) next b))))

(defun ident (x) x)

(defun sum-int (a b)
  (sum #'ident a #'1+ b))

Or more CLish, without explicitly defuning ident:

(defun sum-int (a b)
  (sum (lambda (x) x) a #'1+ b))

You need #' quoting to get a function object since CL has separate namespaces for functions (defined with defun) and variables.

ivans
Also note that CL has a global function namespace, so that original ident-in-sumint will cause warnings on every execution - it will redefine the function on every run of sum-int, so I ripped it out of sum-int.
ivans
Actually, defuning ident just to show that you can is kind of pointless. I'll rewrite this in a more CLish way... just a jiffy...
ivans
I have a growing suspicion that this would look bloody messy to a Schemer, what with the funcalls and #' quoting :-(
ivans
all this is only exercise - not real programm)
Stas
+1  A: 
(defun sum (term a next b)
  (if (> a b)
      0
      (+ (funcall term a) (sum term (funcall next a) next b))))

(defun sum-int (a b)
  (flet ((ident (x) x))
   (sum #'ident a #'1+ b)))

Just another CL take with FLET (untested).

Will Hartung
Common Lisp already has `identity`, you do not need to define it.
Svante
I was rewriting the example given. The question was about defining functions, and thus the example with FLET, not the identity function.
Will Hartung