Can someone please guide me or explain how to perform backtracking in LISP ? Any examples or links would be appreciated.
I did try to google , however none of them had simple example enough for me to understand.
Thanks
The typical way is to have non-mutable state passed down the call-stack, with helper functions taking the current state-returning a new state to "fake" mutation.
A possible (although rather suboptimal) sudoku-solver would then be:
;;; Use a list of 81 integers to represent a sudoku board,
;;; each number 1-9 represents itself, 0 represents a blank
(defun sudoku-solver (board)
(cond ((notany #'zerop board)
(if (sudoku-solved-p board)
board
nil))
(t (let ((positions (sudoku-all-blanks board)))
(loop for position in positions
do (loop for number in '(1 2 3 4 5 6 7 8 9)
do (let ((result (sudoku-solver
(sudoku-set board
position
number))))
(when result
(return-from sudoku-solver result)))))))))
This will automatically backtrack until a solution is found. I have skipped obscuring the demonstration with the support code that would turn it from a demonstration to actual working code.
Related
I have an assignment for class specifically testing our understanding of do, asking to define a function to produce the minimum of a list of numbers. We are asked to also use a secondary function ("smaller") to do so.
I have no previous experience coding, and am forced to stay within the boundaries of do; I've been reading up on the issue as much as I can, but almost everything I find just suggests using other methods (do*, COND, etc.).
I defined a simple "smaller" as:
(defun smaller (x y)
(if (< x y) x y))
I then approached the problem as such:
(defun minimum (lst)
"(lst)
Returns the minimum of a list of numbers."
(do ((numbers lst (cdr numbers))
(min (car numbers) (smaller min (cadr numbers))))
((null numbers) min)))
I feel there's an issue where the "smaller" function can't be applied on the first loop (feedback about this would be great), otherwise my immediate issue is getting an error of: "UNBOUND-VARIABLE" for the variable "NUMBERS". I am not sure which 'area' is causing the confusion: if I have poorly formatted the do loop entirely, or if one of the second/third/etc. "numbers" is causing an issue.
Can someone provide some feedback? -- again keeping in mind that we are limited specifically to simple do loops, and that I definitely don't have a perfect understanding of what I've already got down.
Thanks so much in advance.
Do binds in parallel, so numbers is not bound when min is first bound. You could fix that by using (car lst) instead of (car numbers) there.
You need to fix the end condition then: (cadr numbers) is nil on the last iteration, you need to stop before that.
For better readability, I'd suggest to use first and second instead of car and cadr here.
You could still refer to numbers as long as you used do*, which is a sequentially binding variant of do. Then you'd have to use car instead of cadr - you're now picking the first number from an already reduced list. And you'd need to modify your end condition to avoid calling smaller with a NIL argument - you should be able to figure this out easily.
Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 9 years ago.
Improve this question
This is a follow up to my previous question. I’m not convinced that Lisp code is as Homoiconic as machine code on a Von Neumann architecture. It seems obvious to me that in both cases code is represented as data, but it also seems apparent that you can exploit this property much more freely in machine code than you can in Lisp.
When mucking around with machine code, self modifying code is so easy it happens all the time, often by accident and with (in my experience) hilarious results. While writing a simple “print the numbers 0-15” program I might have an “off by one” error with one of my pointers. I’ll end up accidentally dumping whatever is in Register 1 into the address in memory that contains the next instruction, and a random instruction gets executed instead. (Always great when it’s some sort of “goto”. God knows where it’s going to end up and what it’s going to do after that happens)
There really is no separation between code and data. Everything is simultaneously an instruction (even if it’s just a NOP), a pointer, and a plain old number. And it’s possible for the code to change before your eyes.
Please help me with a Lisp scenario I’ve been scratching my head over. Say I’ve got the following program:
(defun factorial (n)
(if (<= n 1)
1
(* n (factorial (- n 1)))))
; -- Demonstrate the output of factorial --
; -- The part that does the Self modifying goes here –
; -- Demonstrate the changed output of factorial
Now what I want to happen is to append to this program some Lisp code which will change the * to a +, change the <= to a >=, stick a (+ 1 2 3) somewhere in there, and generally bugger the function up. And then I want the program to execute the absolute mess that results.
Key point: Unless I’ve made some fatal error in the sample code you’re only allowed to alter the -– More code goes here –- part. What you see above is the code. I don’t want you quoting the entire list and storing it in a variable so that it can be manipulated and spat out as a separate function with the same name; I don’t want a standard redefinition of factorial as something completely different. I want that code, right there that I can see on my screen to change itself before my eyes, just like machine code.
If this is an impossible/unreasonable request then it only solidifies further in my mind the idea that Homoiconicity is not a discrete property that a language either has or doesn’t have, it is a spectrum and Lisp isn't at the bleeding edge. (Alternatively Lisp is as Homoiconic as they come and I'm looking for some other term to describe machine-code-esque self-modification)
That's easy. You only need to change the list representation. All you need is a Lisp interpreter.
The Common Lisp implementation LispWorks provides us with a Lisp interpreter:
CL-USER 137 > (defun factorial (n)
(if (<= n 1)
1
(* n (factorial (- n 1)))))
FACTORIAL
CL-USER 138 > (fifth (function-lambda-expression #'factorial))
(IF (<= N 1) 1 (* N (FACTORIAL (- N 1))))
CL-USER 139 > (fourth (fifth (function-lambda-expression #'factorial)))
(* N (FACTORIAL (- N 1)))
CL-USER 140 > (setf (first (fourth (fifth (function-lambda-expression
#'factorial))))
'+)
+
CL-USER 141 > (fourth (fifth (function-lambda-expression #'factorial)))
(+ N (FACTORIAL (- N 1)))
CL-USER 142 > (factorial 10)
55
CL-USER 143 > (setf (first (fourth (fifth (function-lambda-expression
#'factorial))))
'*)
*
CL-USER 144 > (factorial 10)
3628800
Here is an example where a function modifies itself. To make it slightly easier, I use a feature of Common Lisp: it allows me to write code which is not just some nested list, but a graph. In this case the function can access its own code:
CL-USER 180 > (defun factorial (n)
(if (<= n 1)
1
(progn
(setf (first '#1=(* n (factorial (- n 1))))
(case (first '#1#)
(+ '*)
(* '+)))
#1#)))
FACTORIAL
Above function alternatively uses + or * by modifying its code.
#1= is a label in the expression, #1# then references that label.
CL-USER 181 > (factorial 10)
4555
In earlier times (70s/80s) in some Lisp groups the developers were not using a text editor to write Lisp code, but a structure editor. The editor commands were directly changing the structure of the Lisp code.
I'm looking for the standard way to represent negative infinity in Lisp. Is there a symblic value which is recognised by Lisp's arithmetic functions as less than all other numbers?
Specifically, I'm looking for an elegant way to write the following:
(defun largest (lst)
"Evaluates to the largest number in lst"
(if (null lst)
***negative-inifinity***
(max (car lst) (largest (cdr lst)))))
ANSI Common Lisp has bignum, which can used to represent arbitrarily large numbers as long as you have enough space, but it doesn't specify an "infinity" value. Some implementations may, but that's not part of the standard.
In your case, I think you've got to rethink your approach based on the purpose of your function: finding the largest number in a list. Trying to find the largest number in an empty list is invalid/nonsense, though, so you want to provide for that case. So you can define a precondition, and if it's not met, return nil or raise an error. Which in fact is what the built-in function max does.
(apply #'max '(1 2 3 4)) => 4
(apply #'max nil) => error
EDIT: As pointed by Rainer Joswig, Common Lisp doesn't allow arbitrarily long argument lists, thus it is best to use reduce instead of apply.
(reduce #'max '(1 2 3 4))
There is nothing like that in ANSI Common Lisp. Common Lisp implementations (and even math applications) differ in their representation of negative infinity.
For example in LispWorks for double floats:
CL-USER 23 > (* MOST-NEGATIVE-DOUBLE-FLOAT 10)
-1D++0
I'm trying to write a function that can calculate GPA. Now I can do limited calculation(only 3 ),but I stuck on how to calculate more , without using loop or recursion (that's the requirement of subject) how to expend nth function? like: (nth n) ,if so ,is that mean i need to write a lambda expression? As an newbie, I maynot describe the question clearly, really need some help..
Glist is grade points Clist is credit hours.
GPA=( gradepoint *credithour + gradepoint *credithour) / ( the sum of credithour) like: (3*1+3*2+4*1)/(1+2+1)
here is my code:
(defun gpa (Glist Clist)
(format t "~3,2f~%"
(/
(+(nth 0 (mapcar #' * Glist Clist))
(nth 1 (mapcar #' * Glist Clist))
(nth 2 (mapcar #' * Glist Clist)))
(+ (nth 0 Clist)
(nth 1 Clist)
(nth 2 Clist))
);end "/"
);end "format"
(values) );end
EDIT
This seems like a good opportunity to emphasize some common (little c) Lisp ideas, so I fleshed out my answer to illustrate.
As mentioned in another answer, you could use a sum function that operates on lists (of numbers):
(defun sum (nums)
(reduce #'+ nums))
The dot product is the multiplicative sum of two (equal-length) vectors:
(defun dot-product (x y)
(sum (mapcar #'* x y)))
The function gpa is a simple combination of the two:
(defun gpa (grades credits)
(/ (dot-product grades credits) (sum credits)))
The example from the question results in the answer we expect (minus being formatted as a float):
(gpa '(3 3 4) '(1 2 1))
> 13/4
There are a few things worth mentioning from this example:
You should learn about map, reduce, and their variants and relatives. These functions are very important to Lisp and are very useful for operating on lists. map* functions generally map sequences to a sequence, and reduce usually transforms a sequence into to a single value (you can however use forms like (reduce #'cons '(1 2 3))).
This is a good example of the "bottom-up" approach to programming; by programming simple functions like sum that are often useful, you make it easy to write dot-product on top of it. Now the gpa function is a simple, readable function built on top of the other two. These are all one-liners, and all are easily readable to anyone who has a basic knowledge of CL. This is in contrast to the methodology usually applied to OOP.
There is no repetition of code. Sure, sum is used more than once, but only where it makes sense. You can do very little more to abstract the notion of a sum of the elements of a list. It's more natural in Scheme to write functions with functions, and that's a whole different topic. This is a simple example, but no two functions are doing the same thing.
If you're using nth to traverse a list, you're doing it wrong. In this case, you might want to write a summing function:
(defun sum (items)
(reduce #'+ items))
I trying to iterate through a sequence, conditionally perform an operation on each element and then collect it (but only if it matched the criteria). Here is a simplified example that works, I just want to know if this is proper or best practice in lisp:
(loop for n in '(1 2 3 4 5)
when (when (equal (mod n 2) 0) n )
collect it)
yields
(2 4)
This works, it just looks funny to me and not so much of the when-when but because I feel like I am having to rig the condition to return what I want. I get that the anaphoric it works on the evaluation of the when but this just seems a little artificial to me. Am I missing something? I have only been a lisper for a few weeks.
Edit: Actually, I am somewhat confused when I tried to apply this. What I really want to do is this:
(loop for n in '(1 2 3 4 5)
when (when (equal (mod n 2) 0) n)
collect it
do (format t "~A" it))
but the second it seems to become unbound... how do I do this?
I don't see why you need anaphor here.
(loop for n in '(1 2 3 4 5)
when (evenp n)
collect n and
do (format t "~A" n))
Delete the keyword AND if you want the FORMAT unconditionally.