I have some trouble fully understanding CL's Loop macro.
This is my code for Project Euler Nr. 32:
(defun number-to-list (nr)
(map 'list #'digit-char-p (prin1-to-string nr)))
(defun nine-digits-p (multiplicand multiplier )
(= (length (equationlist multiplicand multiplier
(* multiplicand multiplier))) 9))
(defun equationlist (multiplicand multiplier product)
(append (number-to-list multiplicand) (number-to-list multiplier)
(number-to-list product)))
(defun pandigital (multiplicand multiplier)
(equal (sort (equationlist multiplicand multiplier
(* multiplicand multiplier)) #'<)
'(1 2 3 4 5 6 7 8 9)))
(defun pandigital-list ()
(loop
for i from 1 to 2000 collect
(loop for j from 2 to 2000
when (and (nine-digits-p i j) (pandigital i j)) collect (* i j))))
(defun euler-32 ()
(reduce #'+ (reduce #'union (pandigital-list))))
Although this gives me the correct solution, my problem is with function "pandigital-list". Instead of collecting only the pandigital numbers, it returns a list filled with "NIL" and the few correct numbers.
How do I change this function to only return the numbers I am interested in ?
The problem is that the inner loop returns nil whenever it does not collect anything else. (Remember: in Common Lisp everything has a value.)
One solution is to redefine pandigital-list like this:
(defun pandigital-list ()
(loop for i from 1 to 2000
for sublist = (loop for j from 2 to 2000
when (and (nine-digits-p i j)
(pandigital i j))
collect (* i j))
when sublist collect sublist))
Related
I am very new to LISP (so forgive me for any dumb mistakes) and the first lab of the year states:
Define a function, STDEV that will compute the standard deviation of a list of numbers (look up formula)
I wrote this code but I don't know why it refuses to work:
(defun stdev (x)
(sqrt (/ (apply '+ (expt (- x (/ (apply '+ x)
(length x)))
2))
(length x))))
(setq a '(1 2 3 4 5))
(STDEV a)
But on runtime it produces the error:
(1 2 3 4 5) is not a number
I believe that I have correctly emulated the standard deviation formula (though I wouldn't put it past myself to make a dumb mistake), but why does my program not like the list of numbers that I give it to evaluate? It is most likely a simple mistake with inputs from this new style of coding but any and all help is greatly appreciated!
Use indentation. I've edited your question:
(defun stdev (x)
(sqrt (/ (apply '+ (expt (- x (/ (apply '+ x)
(length x)))
2))
(length x))))
expt returns a number. You call (apply '+ some-number)?
Also you subtract a number from a list.
Why?
Generally I would recommend to use a Lisp listener (aka REPL) to get to working code:
Compute the mean value:
CL-USER 21 > (let ((l (list 1 2 3 4 5)))
(/ (reduce #'+ l)
(length l)))
3
Subtract the mean value and square using mapcar:
CL-USER 22 > (mapcar (lambda (item)
(expt (- item 3) 2))
(list 1 2 3 4 5))
(4 1 0 1 4)
Compute the variance as the mean value of above:
CL-USER 23 > (let ((l (list 4 1 0 1 4)))
(/ (reduce #'+ l)
(length l)))
2
Take the square root to get the standard deviation:
CL-USER 24 > (sqrt 2)
1.4142135
Then you only need to assemble it into a few functions: average, variance and standard-deviation.
You’re taking - a ..., when a is your list.
Not a complete answer, because this is homework, but: you want to calculate the mean first, you can implement a sum function, which you will need twice, with a fold, and you can apply a helper function or lambda expression to every element of a list using a map.
I'm trying to write the "closest" function,in Lisp, without using setq/setf etc...
The function finds the nearest vector of a given vector (finding it on a list of lists).
I tried but without sets is too hard,thanks a lot.
Usually the updating of variable is done by recursion:
(defun main-function (arg)
(main-function-helper arg 0 1))
(defun main-function-helper (arg var1 var2)
(if (= arg var1)
var2
(main-function-helper arg (1+ var1) (1+ var2))))
When you're done you can put the helper into the main function:
(defun main-function (arg)
(labels ((helper (var1 var2) ; arg left out since it's not changed
(if (= arg var1)
var2
(helper (1+ var1) (1+ var2)))))
(helper 0 1)))
This is of course a silly implementation of 1+ for positive arguments.
Without set, returns a list of lists in case there are ties:
(NOTE: loop macro uses set at some point :P)
(defun euclid (v1 v2)
(sqrt (loop for x in v1 for y in v2 sum
(expt (- x y) 2))))
(defun closest (target listoflists distancefn)
(loop for l in listoflists for d = (apply distancefn (list target l))
minimizing d into min
collecting (list l d) into col
finally (return
(loop for (vec dis) in col when
(eql dis min) collect vec))))
(closest '(1 2 3) '((1 2 2) ( 1 2 2) ( 2 2 2)) #'euclid)
> ((1 2 2) (1 2 2))
I'm trying to get the largest sublist from a list using Common Lisp.
(defun maxlist (list)
(setq maxlen (loop for x in list maximize (list-length x)))
(loop for x in list (when (equalp maxlen (list-length x)) (return-from maxlist x)))
)
The idea is to iterate through the list twice: the first loop gets the size of the largest sublist and the second one retrieves the required list. But for some reason I keep getting an error in the return-from line. What am I missing?
Main problem with loop
There are a few problems here. First, you can write the loop as the following. There are return-from and while forms in Common Lisp, but loop defines its own little language that also recognizes while and return, so you can just use those:
(loop for x in list
when (equalp maxlen (list-length x))
return x)
A loop like this can actually be written more concisely with find though. It's just
(find maxlen list :key list-length :test 'equalp)
Note, however, that list-length should always return a number or nil, so equalp is overkill. You can just use eql, and that's the default for find, so you can even write
(find maxlen list :key list-length)
list-length and maximize
list-length is a lot like length, except that if a list has circular structure, it returns nil, whereas it's an error to call length with an improper list. But if you're using (loop ... maximize ...), you can't have nil values, so the only case that list-length handles that length wouldn't is one that will still give you an error. E.g.,
CL-USER> (loop for x in '(4 3 nil) maximize x)
; Evaluation aborted on #<TYPE-ERROR expected-type: REAL datum: NIL>.
(Actually, length works with other types of sequences too, so list-length would error if you passed a vector, but length wouldn't.) So, if you know that they're all proper lists, you can just
(loop for x in list
maximizing (length x))
If they're not all necessarily proper lists (so that you do need list-length), then you need to guard like:
(loop for x in list
for len = (list-length x)
unless (null len) maximize len)
A more efficient argmax
However, right now you're making two passes over the list, and you're computing the length of each sublist twice. Once is when you compute the maximum length, and the other is when you go to find one with the maximum value. If you do this in one pass, you'll save time. argmax doesn't have an obvious elegant solution, but here are implementations based on reduce, loop, and do*.
(defun argmax (fn list &key (predicate '>) (key 'identity))
(destructuring-bind (first &rest rest) list
(car (reduce (lambda (maxxv x)
(destructuring-bind (maxx . maxv) maxxv
(declare (ignore maxx))
(let ((v (funcall fn (funcall key x))))
(if (funcall predicate v maxv)
(cons x v)
maxxv))))
rest
:initial-value (cons first (funcall fn (funcall key first)))))))
(defun argmax (function list &key (predicate '>) (key 'identity))
(loop
for x in list
for v = (funcall function (funcall key x))
for maxx = x then maxx
for maxv = v then maxv
when (funcall predicate v maxv)
do (setq maxx x
maxv v)
finally (return maxx)))
(defun argmax (function list &key (predicate '>) (key 'identity))
(do* ((x (pop list)
(pop list))
(v (funcall function (funcall key x))
(funcall function (funcall key x)))
(maxx x)
(maxv v))
((endp list) maxx)
(when (funcall predicate v maxv)
(setq maxx x
maxv v))))
They produce the same results:
CL-USER> (argmax 'length '((1 2 3) (4 5) (6 7 8 9)))
(6 7 8 9)
CL-USER> (argmax 'length '((1 2 3) (6 7 8 9) (4 5)))
(6 7 8 9)
CL-USER> (argmax 'length '((6 7 8 9) (1 2 3) (4 5)))
(6 7 8 9)
Short variant
CL-USER> (defparameter *test* '((1 2 3) (4 5) (6 7 8 9)))
*TEST*
CL-USER> (car (sort *test* '> :key #'length))
(6 7 8 9)
Paul Graham's most
Please, consider also Paul Graham's most function:
(defun most (fn lst)
(if (null lst)
(values nil nil)
(let* ((wins (car lst))
(max (funcall fn wins)))
(dolist (obj (cdr lst))
(let ((score (funcall fn obj)))
(when (> score max)
(setq wins obj
max score))))
(values wins max))))
This is the result of test (it also returns value that's returned by supplied function for the 'best' element):
CL-USER> (most #'length *test*)
(6 7 8 9)
4
extreme utility
After a while I came up with idea of extreme utility, partly based on Paul Graham's functions. It's efficient and pretty universal:
(declaim (inline use-key))
(defun use-key (key arg)
(if key (funcall key arg) arg))
(defun extreme (fn lst &key key)
(let* ((win (car lst))
(rec (use-key key win)))
(dolist (obj (cdr lst))
(let ((test (use-key key obj)))
(when (funcall fn test rec)
(setq win obj rec test))))
(values win rec)))
It takes comparison predicate fn, list of elements and (optionally) key parameter. Object with the extreme value of specified quality can be easily found:
CL-USER> (extreme #'> '(4 9 2 1 5 6))
9
9
CL-USER> (extreme #'< '(4 9 2 1 5 6))
1
1
CL-USER> (extreme #'> '((1 2 3) (4 5) (6 7 8 9)) :key #'length)
(6 7 8 9)
4
CL-USER> (extreme #'> '((1 2 3) (4 5) (6 7 8 9)) :key #'cadr)
(6 7 8 9)
7
Note that this thing is called extremum in alexandria. It can work with sequences too.
Using recursion:
(defun maxim-list (l)
(flet ((max-list (a b) (if (> (length a) (length b)) a b)))
(if (null l)
nil
(max-list (car l) (maxim-list (cdr l))))))
The max-list internal function gets the longest of two list. maxim-list is getting the longest of the first list and the maxim-list of the rest.
I have a list in Elisp. How do i return a list consisting of every nth element starting from the 1st? In Python i have slice notation:
>>> range(10)[::3]
[0, 3, 6, 9]
I can't find anything helpful in dash.el list API, so i wrote my solution using loop macro:
(defun step (n xs)
(loop for x in xs by (lambda (xs) (nthcdr n xs))
collect x))
ELISP> (step 3 (number-sequence 0 10))
(0 3 6 9)
By the way, (lambda (xs) (nthcdr n xs)) could be rewritten with dash.el's partial application function -partial: (-partial 'nthcdr n).
loop macro seems like overkill. How do i return elements by step in Emacs Lisp?
dash package's slice supports step from version 2.7. Therefore Python's range(10)[1:7:2] is equivalent to:
(-slice (number-sequence 0 9) 1 7 2) ; (1 3 5)
Here's a short illustration, comparing using -partial and a plain lambda in a loop:
(require 'cl-lib)
(prog1 nil
(setq bigdata (number-sequence 1 10000)))
(defun every-nth-1 (n xs)
(cl-loop for x in xs by (lambda (xs) (nthcdr n xs))
collect x))
(defun every-nth-2 (n xs)
(cl-loop for x in xs by (-partial 'nthcdr n)
collect x))
(defmacro util-timeit (expr)
(let ((t-beg (float-time))
(res (dotimes (i 1000)
(eval expr)))
(t-end (float-time)))
(/
(- t-end t-beg)
1000)))
(setq time1
(util-timeit
(length (every-nth-1 3 bigdata))))
(setq time2
(util-timeit
(every-nth-2 3 bigdata)))
(message "%s" (/ time2 time1))
Calling eval-buffer gives me a result around 4. This means that
(lambda (xs) (nthcdr n xs)) is 4 times faster than (-partial 'nthcdr n),
at least without byte compilation.
With byte-compilation, it gives an astounding 12.2-13.6 times difference in performance
in favor of a plain lambda!
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 10 years ago.
Improve this question
I just started learning common lisp and so I've been working on project euler problems. Here's my solution (with some help from https://github.com/qlkzy/project-euler-cl ). Do you guys have any suggestions for stylistic changes and the sort to make it more lisp-y?
; A palindromic number reads the same both ways. The largest palindrome made
; from the product of two 2-digit numbers is 9009 = 91 99.
; Find the largest palindrome made from the product of two 3-digit numbers.
(defun num-to-list (num)
(let ((result nil))
(do ((x num (truncate x 10)))
((= x 0 ) result)
(setq result (cons (mod x 10) result)))))
(defun palindrome? (num)
(let ((x (num-to-list num)))
(equal x (reverse x))))
(defun all-n-digit-nums (n)
(loop for i from (expt 10 (1- n)) to (1- (expt 10 n)) collect i))
(defun all-products-of-n-digit-nums (n)
(let ((nums (all-n-digit-nums n)))
(loop for x in nums
appending (loop for y in nums collecting (* x y)))))
(defun all-palindromes (n)
(let ((nums (all-products-of-n-digit-nums n)))
(loop for x in nums
when (palindrome? x) collecting x)))
(defun largest-palindrome (n)
(apply 'max (all-palindromes 3)))
(print (largest-palindrome 3))
Barnar's solution is great however there's just a small typo, to return a result it should be:
(defun largest-palindrome (n)
(loop with start = (expt 10 (1- n))
and end = (1- (expt 10 n))
for i from start to end
maximize (loop for j from i to end
for num = (* i j)
when (palindrome? num)
maximize num)))
(setq list (cons thing list))
can be simplified to:
(push thing list)
My other comments on your code are not so much about Lisp style as about the algorithm. Creating all those intermediate lists of numbers seems like a poor way to do it, just write nested loops that calculate and test the numbers.
(defun all-palindromes (n)
(loop for i from (expt 10 (1- n)) to (1- (expt 10 n))
do (loop for j from (expt 10 (1- n)) to (1- (expt 10 n))
for num = (* i j)
when (palindrome? num)
collect num)))
But LOOP has a feature you can use: MAXIMIZE. So instead of collecting all the palindroms in a list with COLLECT, you can:
(defun largest-palindrome (n)
(loop with start = (expt 10 (1- n))
and end = (1- (expt 10 n))
for i from start to end
do (loop for j from start to end
for num = (* i j)
when (palindrome? num)
maximize num)))
Here's another optimization:
(defun largest-palindrome (n)
(loop with start = (expt 10 (1- n))
and end = (1- (expt 10 n))
for i from start to end
do (loop for j from i to end
for num = (* i j)
when (palindrome? num)
maximize num)))
Making the inner loop start from i instead of start avoids the redundancy of checking both M*N and N*M.
The example below is a bit contrived, but it finds the palindrome in a lot less iterations than your original approach:
(defun number-to-list (n)
(loop with i = n
with result = nil
while (> i 0) do
(multiple-value-bind (a b)
(floor i 10)
(setf i a result (cons b result)))
finally (return result)))
(defun palindrome-p (n)
(loop with source = (coerce n 'vector)
for i from 0 below (floor (length source) 2) do
(when (/= (aref source i) (aref source (- (length source) i 1)))
(return))
finally (return t)))
(defun suficiently-large-palindrome-of-3 ()
;; This is a fast way to find some sufficiently large palindrome
;; that fits our requirement, but may not be the largest
(loop with left = 999
with right = 999
for maybe-palindrome = (number-to-list (* left right)) do
(cond
((palindrome-p maybe-palindrome)
(return (values left right)))
((> left 99)
(decf left))
((> right 99)
(setf left 999 right (1- right)))
(t ; unrealistic situation
; we didn't find any palindromes
; which are multiples of two 3-digit
; numbers
(return)))))
(defun largest-palindrome-of-3 ()
(multiple-value-bind (left right)
(suficiently-large-palindrome-of-3)
(loop with largest = (* left right)
for i from right downto left do
(loop for j from 100 to 999
for maybe-larger = (* i j) do
(when (and (> maybe-larger largest)
(palindrome-p (number-to-list maybe-larger)))
(setf largest maybe-larger)))
finally (return largest)))) ; 906609
It also tries to optimize a bit the way you check that number is a palindrome, for an additional memory cost though. It also splits the number into a list using somewhat longer code, but making less divisions (which are somewhat computationally expensive).
The whole idea is based on the concept that the largest palindrome will be somewhere more towards the... largest multipliers, so, by starting off with 99 * 99 you will have a lot of bad matches. Instead, it tries to go from 999 * 999 and first find some palindrome, which looks good, doing so in a "sloppy" way. And then it tries hard to improve upon the initial find.