I'm writing a program in Lisp(common lisp dialect)..
I want the program to count the number of sublists in a list..
This is what I have written till now:
(defun llength (L)
(cond
((null L) 0)
((list (first L)) (progn (+ (llength (first L)) 1) (llength (rest L))))
((atom (first L)) (llength (rest L)))
)
)
The function returns the error "Unbound variable: LLENGTH" and I don't understand why or how I can fix it..
Any suggestions ?
You have multiple errors in your code.
First of all, list function creates new list, not checking if it is a list. The function you need is listp - "p" at the end means "predicate".
Second, (progn (+ (llength (first L)) 1) (llength (rest L)) will not increase counter. progn performs expressions one by one and returns result of the last expression, other results are just thrown out. progn is there mostly for side effects. What you actually need is addition of all three components: 1 to indicate one found list, result of applying function to the first element and result for applying to the rest. So, this line must be:
((listp (first L)) (+ (llength (first L)) (llength (rest L)) 1))
More errors may exist, please, be careful to indent code correctly - it really helps to reduce them.
When you define a function with the (defun function name (parameters)) call you must then call the function by typing:
(function name (parameters))
Perhaps you were simply typing:
function name (parameters)
Doing this will get you the error you are receiving so be sure to encompass your whole statement in parenthesis.
(defun llength (list)
(cond
((null list) 0)
((listp (first list))
;; 1 + the count of any sub-lists in this sub-list + the
;; count of any sub-lists in the rest of the list.
(+ 1 (llength (first list))
(llength (rest list))))
(t (llength (rest list)))))
Test:
> (llength '(1 2 3 4))
0
> (llength '(1 2 (3 4)))
1
> (llength '(1 2 (3 (4))))
2
> (llength '(1 2 (3 4) (5 6) (7 8) (9 (10 (11)))))
6
Related
This question already has answers here:
Common lisp error: "should be lambda expression"
(4 answers)
Closed 5 years ago.
I'm trying to make a function that changes infix input to prefix eg : (x + 1) as input outputted as (+ x 1).
So here is my code for the moment :
(setq x '(Y + 1))
(if (listp x ) (list (second x) (first x) (first (last x))) x)
so it returns (+ Y 1) if I input a list and the user input if it's not a list.
However, the problem is that I can't get this code working in a function :
(defun prefixToInfix (x)(
(if (listp x ) (list (second x) (first x) (first (last x))) x)
)
)
the function is indeed created but when I call it
(prefixtoinfix '(Y + 1))
I get an error
Error: Illegal function object: (IF (LISTP X) (LIST # # #) X).
[condition type: TYPE-ERROR]
I don't know why my if statement works in the main program but doesn't when I run it from my function.
What you are missing is that in Lisp parentheses are meaningful.
In C/Java/Python &c, the following expressions are the same:
a+b
(a+b)
(a)+(b)
(((a)+(b)))
(((((a)+(b)))))
In Lisp, the following expressions are very different:
a --- a symbol
(a) --- a list with a single element, which is the symbol a
(1 (2)) --- a list of two elements:
number 1
list of of length 1, containing number 2
In your case, function (note indentation and paren placement!)
(defun prefixToInfix (x)
((if (listp x) (list (second x) (first x) (first (last x))) x)))
has extra parens around if (and this causes the whole if form to be interpreted as a function, with disastrous results), and should be (note line breaks and indentation - lispers do not count parens, they look at indentation to understand the code, see http://lisp-lang.org/style-guide/)
(defun prefix-to-infix (x)
(if (listp x)
(list (second x)
(first x)
(first (last x)))
x))
PS. See also recommendations in want to learn common lisp.
DrRacket user.
I'm struggling to understand how this program works.I wrote it myself and it does what it must but I can't understand how.
I define while loops as:
(define (while test body)
(if (test)
(begin
(body)
(while test body))
(void)))
Now I need to write a program that applies the given procedure to each element of a mutable list.
Here what I wrote:
(define (mlist-map-while f x)
(while (lambda() (not (null? x)))
(lambda ()
(set-mcar! x (f (mcar x)))
(set! x (mcdr x))))
(void))
So, defining
list1 (mlist 1 2 3)
and applying
(mlist-map-while (lambda (x) (+ x 1)) list1)
we get '(2 3 4).
The thing that I don't understand is how the first element of the list stays in it, because if it's done how I wrote here
(set! x (mcdr x))
the first procedure that sets -mcar! must be useless and be overlapped with the second. Like in this example:
(define list1 (mlist 1 2 3))
(set-mcar! list1 9)
(set-mcdr! list1 (mcdr list!))
and we lack the first element, but this program somehow leaves it in and gives the desired output. I would like to know how it works and whether there is another way of traversing the given list.
There is a big difference between set-cdr! abd set!. The first alters the pair's cdr pointer, while the latter alters the binding, thus what the name should point to.
In your mlist-map-while the variable x alters the car, then changes what x represents, to be the cdr of x. It never changes the cdr so your binding list1 always points to the first pair while x points to the first, then second, etc...
Thus it's more like this:
(define list1 (mlist 1 2 3))
(define list1-ref list1) ; variable pointing to the same value as list1
(set-mcar! list1-ref 9) ; set-car! changes the pair
(set! list1-ref (mcdr list)) ; set! updates what list1-ref points to
list1 ; ==> (9 2 3)
list-ref ; ==> (2 3)
You can iterate over a list in the same fashion without using set!, with recursion:
(define (fold function init lst)
(if (null? lst)
init
(fold function
(function (car lst) init)
(cdr lst))))
(fold + 0 '(1 2 3)
; ==> 6
(fold cons '() '(1 2 3))
; ==> (3 2 1)
Notice that here we recurse and change what lst is, to be the cdr. Every recursion has its own lst, which is not to be confused with the caller's own. It ends up doing the same as set! in your example, without mutation.
Here is something you can do in Scheme:
> (define (sum lst acc)
(if (null? lst)
acc
(sum (cdr lst) (+ acc (car lst)))))
> (define sum-original sum)
> (define (sum-debug lst acc)
(print lst)
(print acc)
(sum-original lst acc))
> (sum '(1 2 3) 0)
6
> (set! sum sum-debug)
> (sum '(1 2 3) 0)
(1 2 3)
0
(2 3)
1
(3)
3
()
6
6
> (set! sum sum-original)
> (sum '(1 2 3) 0)
6
If I were to do the following in Common Lisp:
> (defun sum (lst acc)
(if lst
(sum (cdr lst) (+ acc (car lst)))
acc))
SUM
> (defvar sum-original #'sum)
SUM-ORIGINAL
> (defun sum-debug (lst acc)
(print lst)
(print acc)
(funcall sum-original lst acc))
SUM-DEBUG
> (sum '(1 2 3) 0)
6
Now how can I do something like (setf sum #'sum-debug) that would change the binding of a function defined with defun?
Because Common Lisp has a different namespace for functions, you need to use symbol-function or fdefinition.
CL-USER> (defun foo (a)
(+ 2 a))
FOO
CL-USER> (defun debug-foo (a)
(format t " DEBUGGING FOO: ~a" a)
(+ 2 a))
DEBUG-FOO
CL-USER> (defun debug-foo-again (a)
(format t " DEBUGGING ANOTHER FOO: ~a" a)
(+ 2 a))
DEBUG-FOO-AGAIN
CL-USER> (foo 4)
6
CL-USER> (setf (symbol-function 'foo) #'debug-foo)
#<FUNCTION DEBUG-FOO>
CL-USER> (foo 4)
DEBUGGING FOO: 4
6
CL-USER> (setf (fdefinition 'foo) #'debug-foo-again)
#<FUNCTION DEBUG-FOO-AGAIN>
CL-USER> (foo 4)
DEBUGGING ANOTHER FOO: 4
6
CL-USER>
A typical use case for redefining functions in such a way is during debugging. Your example indicates that. Common Lisp already provides higher-level machinery for that: TRACE. Under the hood it sets the function value of the symbol, but it provides a more convenient user interface. Often something like TRACE will have many, non-standard, options.
Tracing functions
The following example uses Clozure Common Lisp, which is always compiling code:
? (defun sum (list accumulator)
(declare (optimize debug)) ; note the debug declaration
(if (endp list)
accumulator
(sum (rest list) (+ accumulator (first list)))))
SUM
? (sum '(1 2 3 4) 0)
10
? (trace sum)
NIL
? (sum '(1 2 3 4) 0)
0> Calling (SUM (1 2 3 4) 0)
1> Calling (SUM (2 3 4) 1)
2> Calling (SUM (3 4) 3)
3> Calling (SUM (4) 6)
4> Calling (SUM NIL 10)
<4 SUM returned 10
<3 SUM returned 10
<2 SUM returned 10
<1 SUM returned 10
<0 SUM returned 10
10
Then to untrace:
? (untrace sum)
Advising functions
In your example you have printed the arguments on entering the function. In many Common Lisp implementations there is another mechanism to augment functions with added functionality: advising. Again using Clozure Common Lisp and its advise macro:
? (advise sum ; the name of the function
(format t "~%Arglist: ~a" arglist) ; the code
:when :before) ; where to add the code
#<Compiled-function (CCL::ADVISED 'SUM) (Non-Global) #x302000D7AC6F>
? (sum '(1 2 3 4) 0)
Arglist: ((1 2 3 4) 0)
Arglist: ((2 3 4) 1)
Arglist: ((3 4) 3)
Arglist: ((4) 6)
Arglist: (NIL 10)
10
What's wrong with my tail-recursive sum procedure? My tail-recursive scheme procedure will not run.
Code:
(define (sum term a next b)
(define iter result i)
(if (> i b)
result
(iter (+ result (term i)) (next i))
(iter 0 a )))
(define (increment x)(+ x 1))
(define (sum-square a b)
(sum (lambda(x)(* x x)) a increment b))
(define (sum-int a b)
(define (identity a) a)
(sum identity a increment b))
(sum-int 5 10)
(sum-square 5 10)
Error:
Error: execute: unbound symbol: "result" [sum-int, (anon), sum, (anon), sum-square, sum, (anon)]
You have parentheses problems in sum. Try this:
(define (sum term a next b)
(define (iter result i)
(if (> i b)
result
(iter (+ result (term i)) (next i))))
(iter 0 a))
In particular, notice that this line was wrong, that's not how you define a procedure:
(define iter result i)
And the corresponding closing parentheses is wrong, too. A strict discipline of correctly indenting and formatting the code will make these kind of errors easier to catch, use a good IDE for this.
A function that returns how many times it has been called in Scheme would look like
(define count
(let ((P 0))
(lambda ()
(set! P (+ 1 P))
P)))
(list (count) (count) (count) (count)) ==> (list 1 2 3 4)
But suppose that we have an expression that looks like this
(map ______ lst)
and we want that to evaluate to
(list 1 2 3 ... n)
where n = (length list)
The problem requires we use a lambda statement in the blank, and we cannot use any auxiliary definitions like (count) in the blank, so
(lambda (x) (count))
is not allowed. Simply replacing (count) with the previous definition like this:
(map
(lambda (x)
((let ((P 0))
(lambda ()
(set! P (+ 1 P))
P))))
L)
doesn't work either.
Any suggestions?
You're very, very close to a correct solution! in the code in the question just do this:
The outermost lambda is erroneous, delete that line and the corresponding closing parenthesis
The innermost lambda is the one that will eventually get passed to the map procedure, so it needs to receive a parameter (even though it's not actually used)
Delete the outermost parenthesis surrounding the let form
It all boils down to this: the lambda that gets passed to map receives a parameter, but also encloses the P variable. The let form defines P only once in the context of the passed lambda, and from that point on the lambda "remembers" the value of P, because for each of the elements in the list the same P is used.
You're 90% of the way there. Use the right-hand-side of your count definition in the blank, and add an (ignored) argument to the function.
(define add-stat-var
(let ( (P '()) )
(lambda (x1)
(if (equal? x1 "ResetStatVar") (set! P '()) (set! P (cons x1 P)))
P
) ;lambda
) ;let
) ;define
(define (test-add-stat-var x)
(let* ( (result '()) )
(set! result (add-stat-var 12))
(set! result (add-stat-var 14))
(set! result (add-stat-var 16))
(display (add-stat-var x)) (newline)
(set! result (add-stat-var "ResetStatVar"))
(display (cdr (add-stat-var x))) (newline)
)
)