newLISP Invalid Function - recursion

I have a homework assignment where we need to write some functions in newLISP. I am running into an issue, so I made an example of the issue to see if anyone can help me out.
The issue is that after a recursive function is over, it returns an ERR: invalid function : error. This happens no matter what the function I am calling is.
For an example, I made a recursive function that decrements a number until we hit 0. This is the code:
(define (decrement num)
(if (> num 0)
(
(println num)
(decrement (- num 1))
)
(
(println "done")
)
)
)
Whenever I run this function, starting with the number 10, the output looks like this:
> (decrement 10)
10
9
8
7
6
5
4
3
2
1
done
ERR: invalid function : ((println "done"))
called from user function (decrement (- num 1))
called from user function (decrement (- num 1))
called from user function (decrement (- num 1))
called from user function (decrement (- num 1))
called from user function (decrement (- num 1))
called from user function (decrement (- num 1))
called from user function (decrement (- num 1))
called from user function (decrement (- num 1))
called from user function (decrement (- num 1))
called from user function (decrement (- num 1))
called from user function (decrement 10)
I cannot figure out why this is returning an invalid function error. I know very little about newLISP, so this may be a simple question.
Thanks!

In Lisp you don't use arbitrary parentheses to group things together. So you should do something like this:
(define (decrement num)
(if (> num 0)
(begin
(println num)
(decrement (- num 1))
)
(println "done")
)
)

Related

User-friendly wrappings for tail recursive functions

I am trying to learn common lisp. I'm familiar with tail recursion, but I'm unfamiliar with the idiomatic way to wrap a tail recursive function in a way that the caller does not have to initialize the accumulator variable(s). Here is an example:
(defun add-em (n s)
(if (eql n 0)
s
(add-em (- n 1) (+ s n))
)
)
Say I wanted to wrap this function so that the user only has to manage inputting n and does not need the full function call (add-em <number> 0). In other languages, such as scala, I would define an inner function and then at the end of the outer function I would call the tail-recursive inner function to run the algorithm.
In common lisp I could define a lambda in the function and use that, but it seems kind of ugly. I figured there may be a more idiomatic way to do it but googling hasn't really given me any results.
Is there a more idiomatic way to do this other than splitting the functions entirely? Or is that the best way? An example:
(defun add-em-inner (num sum)
(if (eql num 0)
sum
(add-em-inner (- num 1) (+ num sum))
)
)
(defun add-em (n)
(add-em-inner n 0)
)
One way is to use the labels operator to define a lexical function that is recursive. So that is to say:
(defun add-em-inner (num sum)
(if (eql num 0)
sum
(add-em-inner (- num 1) (+ num sum))))
(defun add-em (n)
(add-em-inner n 0))
Becomes this:
(defun add-em (n)
(labels ((add-em-inner (num sum)
(if (eql num 0)
sum
(add-em-inner (- num 1) (+ num sum)))))
(add-em-inner n 0)))
If you don't mind the extra accumulator being part of the function's public interface, but care only about user convenience (caller not having to specify the value), you can just make it an optional parameter:
(defun add-em (n &optional (s 0))
(if (eql n 0)
s
(add-em (- n 1) (+ s n))))
There are often good reasons not to do that; for instance, you may want to retain the ability to define an optional argument for future API extension that is backwards compatible. That is still possible here, but only provided that the outside callers don't pass that parameter.

Recursion in Common Lisp, pushing values, and the Fibonacci Sequence

This is not a homework assignment. In the following code:
(defparameter nums '())
(defun fib (number)
(if (< number 2)
number
(push (+ (fib (- number 1)) (fib (- number 2))) nums))
return nums)
(format t "~a " (fib 100))
Since I am quite inexperienced with Common Lisp, I am at a loss as to why the function does not return an value. I am a trying to print first 'n' values, e.g., 100, of the Fibonacci Sequence.
Thank you.
An obvious approach to computing fibonacci numbers is this:
(defun fib (n)
(if (< n 2)
n
(+ (fib (- n 1)) (fib (- n 2)))))
(defun fibs (n)
(loop for i from 1 below n
collect (fib i)))
A little thought should tell you why no approach like this is going to help you compute the first 100 Fibonacci numbers: the time taken to compute (fib n) is equal to or a little more than the time taken to compute (fib (- n 1)) plus the time taken to compute (fib (- n 2)): this is exponential (see this stack overflow answer).
A good solution to this is memoization: the calculation of (fib n) repeats subcalculations a huge number of times, and if we can just remember the answer we computed last time we can avoid doing so again.
(An earlier version of this answer has an overcomplex macro here: something like that may be useful in general but is not needed here.)
Here is how you can memoize fib:
(defun fib (n)
(check-type n (integer 0) "natural number")
(let ((so-far '((2 . 1) (1 . 1) (0 . 0))))
(labels ((fibber (m)
(when (> m (car (first so-far)))
(push (cons m (+ (fibber (- m 1))
(fibber (- m 2))))
so-far))
(cdr (assoc m so-far))))
(fibber n))))
This keeps a table – an alist – of the results it has computed so far, and uses this to avoid recomputation.
With this memoized version of the function:
> (time (fib 1000))
Timing the evaluation of (fib 1000)
User time = 0.000
System time = 0.000
Elapsed time = 0.000
Allocation = 101944 bytes
0 Page faults
43466557686937456435688527675040625802564660517371780402481729089536555417949051890403879840079255169295922593080322634775209689623239873322471161642996440906533187938298969649928516003704476137795166849228875
The above definition uses a fresh cache for each call to fib: this is fine, because the local function, fibber does reuse the cache. But you can do better than this by putting the cache outside the function altogether:
(defmacro define-function (name expression)
;; Install EXPRESSION as the function value of NAME, returning NAME
;; This is just to avoid having to say `(setf ...)`: it should
;; probably do something at compile-time too so the compiler knows
;; the function will be defined.
`(progn
(setf (fdefinition ',name) ,expression)
',name))
(define-function fib
(let ((so-far '((2 . 1) (1 . 1) (0 . 0))))
(lambda (n)
(block fib
(check-type n (integer 0) "natural number")
(labels ((fibber (m)
(when (> m (car (first so-far)))
(push (cons m (+ (fibber (- m 1))
(fibber (- m 2))))
so-far))
(cdr (assoc m so-far))))
(fibber n))))))
This version of fib will share its cache between calls, which means it is a little faster, allocates a little less memory but may be less thread-safe:
> (time (fib 1000))
[...]
Allocation = 96072 bytes
[...]
> (time (fib 1000))
[...]
Allocation = 0 bytes
[...]
Interestingly memoization was invented (or at least named) by Donald Michie, who worked on breaking Tunny (and hence with Colossus), and who I also knew slightly: the history of computing is still pretty short!
Note that memoization is one of the times where you can end up fighting a battle with the compiler. In particular for a function like this:
(defun f (...)
...
;; no function bindings or notinline declarations of F here
...
(f ...)
...)
Then the compiler is allowed (but not required) to assume that the apparently recursive call to f is a recursive call into the function it is compiling, and thus to avoid a lot of the overhead of a full function call. In particular it is not required to retrieve the current function value of the symbol f: it can just call directly into the function itself.
What this means is that an attempt to write a function, memoize which can be used to mamoize an existing recursive function, as (setf (fdefinition 'f) (memoize #'f)) may not work: the function f still call directly into the unmemoized version of itself and won't notice that the function value of f has been changed.
This is in fact true even if the recursion is indirect in many cases: the compiler is allowed to assume that calls to a function g for which there is a definition in the same file are calls to the version defined in the file, and again avoid the overhead of a full call.
The way to deal with this is to add suitable notinline declarations: if a call is covered by a notinline declaration (which must be known to the compiler) then it must be made as a full call. From the spec:
A compiler is not free to ignore this declaration; calls to the specified functions must be implemented as out-of-line subroutine calls.
What this means is that, in order to memoize functions you have to add suitable notinline declarations for recursive calls, and this means that memoizing either needs to be done by a macro, or must rely on the user adding suitable declarations to the functions to be memoized.
This is only a problem because the CL compiler is allowed to be smart: almost always that's a good thing!
Your function unconditionally returns nums (but only if a variable called return exists). To see why, we can format it like this:
(defun fib (number)
(if (< number 2)
number
(push (+ (fib (- number 1)) (fib (- number 2))) nums))
return
nums)
If the number is less than 2, then it evaluates the expression number, uselessly, and throws away the result. Otherwise, it pushes the result of the (+ ....) expression onto the nums list. Then it uselessly evaluates return, throwing away the result. If a variable called return doesn't exist, that's an error situation. Otherwise, it evaluates nums and that is the return value.
In Common Lisp, there is a return operator for terminating and returning out of anonymous named blocks (blocks whose name is the symbol nil). If you define a named function with defun, then an invisible block exists which is not anonymous: it has the same name as that function. In that case, return-from can be used:
(defun function ()
(return-from function 42) ;; function terminates, returns 42
(print 'notreached)) ;; this never executes
Certain standard control flow and looping constructs establish a hidden anonymous block, so return can be used:
(dolist (x '(1 2 3))
(return 42)) ;; loop terminates, yields 42 as its result
If we use (return ...) but there is no enclosing anonymous block, that is an error.
The expression (return ...) is different from just return, which evaluates a variable named by the symbol return, retrieving its contents.
It is not clear how to repair your fib function, because the requirements are unknown. The side effect of pushing values into a global list normally doesn't belong inside a mathematical function like this, which should be pure (side-effect-free).
So you might know that if you know the two previous numbers you can compute the next. What comes after 3, 5? If you guess 8 you have understood it. Now if you start with 0, 1 and roll 1, 1, 1, 2, etc you collect the first variable until you have the number of numbers you'd like:
(defun fibs (elements)
"makes a list of elements fibonacci numbers starting with the first"
(loop :for a := 0 :then b
:for b := 1 :then c
:for c := (+ a b)
:for n :below elements
:collect a))
(fibs 10)
; ==> (0 1 1 2 3 5 8 13 21 34)
Every form in Common Lisp "returns" a value. You can say it evaluates to. eg.
(if (< a b)
5
10)
This evaluates either to 5 or 10. Thus you can do this and expect that it evaluates to either 15 or 20:
(+ 10
(if (< a b)
5
10))
You basically want your functions to have one expression that calculates the result. eg.
(defun fib (n)
(if (zerop n)
n
(+ (fib (1- n)) (fib (- n 2)))))
This evaluates to the result og the if expression... loop with :collect returns the list. You also have (return expression) and (return-from name expression) but they are usually unnecessary.
Your global variable num is actually not that a bad idea.
It is about to have a central memory about which fibonacci numbers were already calculated. And not to calculate those already calculated numbers again.
This is the very idea of memoization.
But first, I do it in bad manner with a global variable.
Bad version with global variable *fibonacci*
(defparameter *fibonacci* '(1 1))
(defun fib (number)
(let ((len (length *fibonacci*)))
(if (> len number)
(elt *fibonacci* (- len number 1)) ;; already in *fibonacci*
(labels ((add-fibs (n-times)
(push (+ (car *fibonacci*)
(cadr *fibonacci*))
*fibonacci*)
(cond ((zerop n-times) (car *fibonacci*))
(t (add-fibs (1- n-times))))))
(add-fibs (- number len))))))
;;> (fib 10)
;; 89
;;> *fibonacci*
;; (89 55 34 21 13 8 5 3 2 1 1)
Good functional version (memoization)
In memoization, you hide the global *fibonacci* variable
into the environment of a lexical function (the memoized version of a function).
(defun memoize (fn)
(let ((cache (make-hash-table :test #'equal)))
#'(lambda (&rest args)
(multiple-value-bind (val win) (gethash args cache)
(if win
val
(setf (gethash args cache)
(apply fn args)))))))
(defun fib (num)
(cond ((zerop num) 1)
((= 1 num) 1)
(t (+ (fib (- num 1))
(fib (- num 2))))))
The previously global variable *fibonacci* is here actually the local variable cache of the memoize function - encapsulated/hidden from the global environment,
accessible/look-up-able only through the function fibm.
Applying memoization on fib (bad version!)
(defparameter fibm (memoize #'fib))
Since common lisp is a Lisp 2 (separated namespace between function and variable names) but we have here to assign the memoized function to a variable,
we have to use (funcall <variable-name-bearing-function> <args for memoized function>).
(funcall fibm 10) ;; 89
Or we define an additional
(defun fibm (num)
(funcall fibm num))
and can do
(fibm 10)
However, this saves/memoizes only the out calls e.g. here only the
Fibonacci value for 10. Although for that, Fibonacci numbers
for 9, 8, ..., 1 are calculated, too.
To make them saved, look the next section!
Applying memoization on fib (better version by #Sylwester - thank you!)
(setf (symbol-function 'fib) (memoize #'fib))
Now the original fib function is the memoized function,
so all fib-calls will be memoized.
In addition, you don't need funcall to call the memoized version,
but just do
(fib 10)

Common Lisp: Undefined function k

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))
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)))
(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)))))

Lisp recursive function missing base case on first call

I started programming with lisp yesterday so please excuse if I am making some really newbie mistake. I am trying to create a function which calculates the bell numbers using the bell triangle and my recursive triangle function is not working properly. I am also sure if I got my recursive triangle function working that my recursive bell function is somehow also broken.
When I test my triangle function I get the output:
(defun bell(l n)
(if(< n 1)(list 1))
(if (= n 1)(last l))
(bell (triangle (reverse l) (last l) (list-length l)) (- n 1))
)
(defun triangle(pL nL i)
(if(<= i 0)
(write "equals zero!")
(reverse nL)
)
(triangle pL (append (list (+ (nth i pL) (nth i nL))) nL) (- i 1))
)
(write (triangle '(1) '(1) 0))
=>
"equals zero!""equals zero!"
*** - NTH: -1 is not a non-negative integer
For some reason, it is printing my debug code twice even though the function should be meeting my base case on the first call.
For some reason, it is printing my debug code twice even though the function should be meeting my base case on the first call.
It is printed twice because if is not doing what you think it does. The first if test is true, therefore equals zero! is printed. After that, a recursive call to triangle function is invoked. The test is again true (-1 <= 0), so equals zero! is again printed. Finally, you get an error because nthcdr function is called with -1. I strongly recommend you a good lisp debugger. The one from Lispworks is pretty good.
I honestly don't get the logic of what you were trying to achieve with your code. so I wrote mine:
(defun generate-level (l &optional (result))
"given a list l that represents a triangle level, it generates the next level"
(if (null l) result
(if (null result)
(generate-level l (list (car (last l))))
(generate-level (cdr l) (append result
(list (+ (car l)
(car (last result)))))))))
(defun bell (levels &optional (l))
"generate a bell triangle with the number of labels given by the first parameter"
(unless (zerop levels)
(let ((to-print (if (null l) (list 1) (generate-level l))))
(print to-print)
(bell (1- levels) to-print))))
Things to understand the implementation:
&optional (parameter): this parameter is optional and nil by default.
append concatenates two lists. I'm using it to insert in the back of the list.
let ((to-print x)) creates a new variable binding (local variable) called to-print and initialized to x.
I almost forgot to mention how if works in common lisp:
(if (= x 1) y z) means if x is equal to 1 then return y, otherwise z.
Now if you call the function to create a Bell triangle of 7 levels:
CL-USER 9 > (bell 7)
(1)
(1 2)
(2 3 5)
(5 7 10 15)
(15 20 27 37 52)
(52 67 87 114 151 203)
(203 255 322 409 523 674 877)
NIL
It would be nicer to print it with the appropiate padding, like this:
1
1 2
2 3 5
5 7 10 15
15 20 27 37 52
52 67 87 114 151 203
203 255 322 409 523 674 877
but I left that as an exercise to the reader.
Your ifs don't have any effect. They're evaluated, and produce results, but then you discard them. Just like
(defun abc ()
'a
'b
'c)
would evaluate 'a and 'b to produce the symbols a and b, and then would evaluate 'c to produce the symbol c, which would then be returned. In the case of
(if(<= i 0)
(write "equals zero!") ; then
(reverse nL) ; else
)
you're comparing whether i is less than or equal to zero, and if it is, you print equals zero, and if it's not, you (non-destructively) reverse nL and discard the result. Then you finish the function by making a call to triangle. It seems like you probably want to return the reversed nL when i is less than or equal to zero. Use cond instead, since you can have multiple body forms, as in:
(cond
((<= i 0) (write ...) (reverse nL))
(t (triangle ...)))
You could also use if with progn to group the forms:
(if (<= i 0)
(progn
(write ...)
(reverse nL))
(triangle ...))
Your other function has the same problem. If you want to return values in those first cases, you need to use a form that actually returns them. For instance:
(if (< n 1)
(list 1)
(if (= n 1)
(last l)
(bell #| ... |#)))
More idiomatic would be cond, and using list rather than l, which looks a lot like 1:
(cond
((< n 1) (list 1))
((= n 1) (last list))
(t (bell #| ... |#)))
Thank you all for the explanations. I eventually arrived at the code below. I realized that the if block worked something like..
(if (condition) (execute statement) (else execute this statement))
(defun bell(l n)
(if (< n 2)(last l)
(bell (triangle l (last l) 0) (- n 1))
)
)
(defun triangle(pL nL i)
(if(= i (list-length pL)) nL
(triangle pL (append nL (list (+ (nth i pL) (nth i nL)))) (+ i 1))
)
)
(write (bell (list 1) 10))

Scheme - fibonacci series with nested lambda

Inspired this post .
I trying to implement a fibonacci series with nested lambda -
(( (lambda (x) (x x)) ;; evaluate x on x
((lambda (fibo-gen)) ;; fibo-gen get another func as arg
(lambda (N it second first)
(cond ;; here the body of the above func ..
((= N 1) 1)
((= N 1) 1)
((= N it) (+ second first))
(else (fibo-gen (+ it 1) (+ second first) (second)))
)
)
)
)
5 1 1 1)
It's prompts r5rs:body: no expression in body in: (r5rs:body)
By my examination each function has a "body" here , so what I did wrong ?
Note that the implementation I trying to do here is iterative mode which avoid re-calculate previous series ..
Edit :
Another mode which also works -
(( (lambda (x) (x x)) ;; evaluate x on x
(lambda (fibo-gen) ;; fibo-gen body use another lambda ..
(lambda (N it second first)
(cond ;; here the body of the above func ..
((= N 1) 1)
((= N 2) 1)
((= N it) second)
(else ((fibo-gen fibo-gen) N (+ it 1) (+ second first) second))
)
)
)
)
5 1 1 1)
=> 8
Well, this is quite a contrived way to calculate fibonacci, but nevertheless possible:
(((lambda (x) (x x))
(lambda (fib-gen)
(lambda (it second first)
(if (zero? it)
first
((fib-gen fib-gen) (sub1 it) (+ first second) second)))))
10 1 0) ; here n = 10
=> 55
If you're aiming for a general way for writing a recursive function without using define, first implement the Y-Combinator:
(define (Y X)
((lambda (proc) (proc proc))
(lambda (proc)
(X (lambda args
(apply (proc proc) args))))))
With this, you can write anonymous recursive procedures with a variable number of arguments, for example:
((Y
(lambda (fib-gen)
(lambda (it second first)
(if (zero? it)
first
(fib-gen (sub1 it) (+ first second) second)))))
10 1 0) ; here n = 10
=> 55
(lambda (fibo-gen))
in the second line has no body.

Resources