Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Common Lisp: Undefined function k

Tags:

common-lisp

I'm pretty new to Common Lisp. And I try to build my own operator functions. In the first function I tried to add one to the given number. The second function we do a recursive use of the first in the frequency of m. When I enter totaladd ( 5 3 ) I expect an 8. What can I do about the undefined funciton k?

(defun add1(n)
    (+ n 1)
    )

(write (add1 5))

(defun totaladd (k m)
    (if (eq m 0)
        0
        (totaladd(add1(k) (- m 1)))
    )
)

(write (totaladd 5 3))
like image 693
tgtrmr Avatar asked Feb 13 '26 03:02

tgtrmr


2 Answers

There are three errors in the next line:

(totaladd(add1(k) (- m 1)))

Let's look at it:

(totaladd                 ; totaladd is a function with two parameters
                          ;  you pass only one argument -> first ERROR
  (add1                   ; add1 is a function with one parameter
                          ;  you pass two arguments -> second ERROR
    (k)                   ; K is a variable, but you call it as a function,
                          ;   but the function K is undefined -> third ERROR
    (- m 1)))
like image 124
Rainer Joswig Avatar answered Feb 15 '26 16:02

Rainer Joswig


(defun add1 (n) (+ n 1))

(defun totaladd (k m)
  (if (= m 0) 
      k 
      (add1 (totaladd k (- m 1)))))

There is a extra function for (= ... 0) called zerop which asks whether a number os zero or not. Very frequently used when recursing over numbers as the break condition out of the recursion. There is also an extra function for (- ... 1) or (+ ... 1) because these are common steps when recursing with numbers: (1- ...) and (1+ ...), respectively. (Their destructive forms are (incf ...) and (decf ...), but these are not needed for recursion.)

So, using this, your form becomes:

(defun totaladd (k m)
  (if (zerop m)
      k
      (add1 (totaladd k (1- m)))))
like image 21
Gwang-Jin Kim Avatar answered Feb 15 '26 18:02

Gwang-Jin Kim