There are a few issues with this code. 1) Your first if in sum_of_mult3 is a noop. Nothing it returns can effect the execution of the function. 2) the second if in sum_of_mult3 has only one condition, a direct recursion if the step is a multiple of 3. For most...
1e16 is, in Scheme terms, an inexact number (or in more practical terms, a floating-point number). For (double-precision) floating point numbers above 253 (9007199254740992), the ulp is greater than 1, which means changes by 1 are too small to be represented.† 10000000000000000, on the other hand, is an integer. If...
arguments,lisp,common-lisp,sbcl
You don't need anything beyond &rest: (defun divisible-p (number &rest divisors) "Check whether number is divisible by divisors." (dolist (spec divisors t) ; For each 'divisor' in divisors (etypecase spec ;; If divisor is a list, test if modulus of first value is 0 ;; then compare to second (boolean)...
Assuming your y-or-n-p nil only when the user pressed n you could write your main loop as (defun main () (loop :while (y-or-n-p "Would you like to play again? ") :do (play-one-game))) or at the end of play-one-game, which I would rename play, prompt the user and if he wants...
Just separate concerns: (defun get-stream (stream) (loop for line = (read-line stream nil) while line collect (parse-float line))) (defun get-file (filename) (with-open-file (stream filename) (get-stream stream))) Then you can use get-file like you already do, and (get-stream *standard-input*)....
I see you have tagged functional programming, but the solution you are trying to do is far from functional. A functional approach would be to have a case analysis. The base case would be a empty list. The answer would be 0. The default case would be the length of the...
A single quote followed by the written representation of a value will produce that value: Example: '(1 x "foo") will produce a value that prints as (1 x "foo"). Suppose now that I don't want a literal symbol x in the list. I have a variable x in my program,...
This is because cond is a macro. Try running the following: (macroexpand '(cond ((plusp 10) "positive") ((zerop 10) "negative") (t "zero"))) In SBCL, I get this: (IF (PLUSP 10) (PROGN "positive") (COND ((ZEROP 10) "negative") (T "zero"))) T In CLISP, I get this: "positive" ; T While I can understand...
In general, the idea of mapping is that for any list (define lst (list a b c d ... )) and function f, the value of (map f lst) is the same as the value of (list (f a) (f b) (f c) (f d) ...). Let's simulate evaluation as...
javascript,lisp,common-lisp,parenscript
You could use (values): (ps (lambda () (chain dialog (show)) (values))) This should probably return undefined (but it actually returns null). If you really need undefined, you have it: (ps (lambda () (chain dialog (show)) undefined)) ...
When I try to create a single-float array like this, i get: (make-array 2 :element-type 'double-float :initial-contents #(3.0 4.0)) Are you trying to create an array of single-floats (what your text says) or an array of double-floats (what the code suggests)? To create an array of double-floats, you'd use...
Your recursive addNode (better called add-node if you are a lisper) needs a stop condition. E.g., (add-node (edge-list) (push (car (pop edge-list)) nodes) (when edge-list (add-node (cdr edge-list)))) Note that there is no reason to use recursion here, a simple mapcar would do just fine: (defun extract-nodes (el) (mapcar #'car...
java,lisp,common-lisp,abcl,cl-ppcre
I used QuickLisp to add cl-ppcre (because nothing else worked for me). Here is what I did (load \"~/QuickLisp.lisp\")") (quicklisp-quickstart:install) (load "~/quicklisp/setup.lisp") (ql:quickload :cl-ppcre) First 2 lines are only a one time things. Once quickLisp is installed you can start from line 3....
Your define-class macro does not evaluate its class-slots argument. You can "fix" your code like this: (defmacro define-class (class-name class-slots) `(eval `(defclass ,',class-name () ,@(mapcar #'slot->defclass-slot ,class-slots)))) (macroexpand-1 '(define-class model '(nom id))) (defparameter *test* '(nom id)) (define-class model *test*) Note that you now have to quote the literal second argument...
The problem of your "function one" is that you pass &rest parameter to the format function as is. Passing x to formatdf results in the creating a list containing one parameter, that is bound to allparm. So if you want to just print the first parameter you should write: (formatdf...
loops,documentation,lisp,common-lisp
Try visiting the Common Lisp Hyper Spec, in particular section §6.1 describing the LOOP facility.
You just need basic recursion: (defun rec-filter (predicate seq &optional acc) (cond ((null seq) acc) ((consp seq) (append (rec-filter predicate (car seq) nil) (rec-filter predicate (cdr seq) nil) (if (funcall predicate seq) (cons seq acc) acc))) (t acc))) (rec-filter (lambda (x) (eq (car x) 's)) tree) ;; => ;; ((s...
Because you used (DEFVAR X 1), which declares X to be a global special variable. This then causes every other later binding of X to use dynamic binding: here in (LET ((X .... Style & Convention in Lisp Convention in Lisp: use *X* instead of X for special variables. (defvar...
Lisp implementations often can store some values directly in cons cells: fixnums, characters, ... For everything else a pointer will be stored in the car or cdr. Nowadays almost all implementations which are using cons cells don't use optimizations like cdr-coding. Memory locality usually is improved by using a copying...
nil and () are two ways to express the same concept (the empty list). Traditionally, nil is used to emphasize the boolean value "false" rather than the empty list, and () is used the other way around. The Common LISP HyperSpec says: () ['nil], n. an alternative notation for writing...
So you want to keep only sublist. You can easily do that with remove-if: (defun remove-atoms (lst) (remove-if #'atom lst)) In your recursive code there is a problem with: (or (unterlisten_zurueckgeben (first lst)) (setq unterlisten (cons (first lst) (unterlisten_zurueckgeben (rest lst)))))) Here if the result of (unterlisten_zurueckgeben (first lst)) is...
I would use something like this: CL-USER 86 > (defmacro define-class (class-name) `(defclass ,class-name ()())) DEFINE-CLASS CL-USER 87 > (defun create-data (mode) (funcall (compile nil `(lambda () (define-class ,mode))))) CREATE-DATA CL-USER 88 > (create-data 'bar) #<STANDARD-CLASS BAR 402016CC73> Above uses code generation and the built-in compiler....
sorting,char,comparison,lisp,common-lisp
A is a symbol, not a character. The string functions will accept symbols and use the symbol's name, but the character functions only accept true character objects, which are entered using #\ syntax. So you can do: (string< 'a 'a) (string< 'a 'b) For reference: #\a => character "a" =>...
The function you described seems to be DNF calculation. Here is my solution: (defun dnf (f) (when f (if (consp f) (let ((f-car-dnf (dnf (car f))) (f-cdr-dnf (dnf (cdr f)))) (if (or (null f-cdr-dnf) (every #'consp f)) (append f-car-dnf f-cdr-dnf) (mapcan (lambda (f-cdr-cj) (mapcar (lambda (f-car-cj) (append f-car-cj f-cdr-cj)) f-car-dnf))...
arrays,multidimensional-array,lisp,clisp
Because you are using an array of lists how about: (defun element-of-matrix (matrix i j) (nth j (aref matrix i))) ...
(defmacro returnval (x) `(format t "~a has value ~a." ',x ,x)) CL-USER> (defparameter *forty-two* 42) *FORTY-TWO* CL-USER> (returnval *forty-two*) *FORTY-TWO* has value 42. NIL CL-USER> (let ((x 5)) (returnval x)) X has value 5. NIL If you really want that extra set of parens around the form, you can do...
I'm usually using: (make-pathname :defaults old-path :directory (butlast (pathname-directory oldpath))) The :defaults argument makes sure that all relevant parts of the old pathname are being copied over....
You can get the length of a list with length. (length '(a b c)) ;; 3 You can then go and check that number against the predicate function evenp, which returns T or NIL depending on if the argument is even or not. (evenp 1) ;; NIL (evenp 2) ;;...
A Common Lisp version is almost the same as in Scheme: (defun solution (list) (apply #'mapcar #'+ list)) (solution '((1 2 3) (9 10 11) (3 4 5))) ; ==> (13 16 19) ...
variables,binding,scheme,lisp,common-lisp
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"...
What about this: (defun checkMember (L a) (car (mapcan #'(lambda (e) (and (equal a e) (list T))) L))) Note: it does not recurse into list elements, but the original function did not either....
Strings are not immutable in Common Lisp, they are mutable: * is the last result from the Lisp listener CL-USER 5 > (make-string 10 :initial-element #\-) "----------" CL-USER 6 > (setf (aref * 5) #\|) #\| CL-USER 7 > ** "-----|----" CL-USER 8 > (concatenate 'string "aa" '(#\b #\b)) "aabb"...
list,parameters,lisp,common-lisp,clisp
Short answer: mapcan is destructive. As per the Hyperspec entry on quote, "The consequences are undefined if literal objects (including quoted objects) are destructively modified." The easiest way to fix this is not to use mapcan. (defun subAll (l k d) (cond ((and (atom l) (eq l k)) d) ((and...
Check your else clause: [else (string? (first lst)) (string? (rest lst))] 1) You have two predicate calls that both return some boolean value, but you aren't connecting them in any way. You want to know if all elements in the list are strings, so what boolean operator (and, or, etc.)...
Read up on mapcar et al: (defparameter a (list 1 2 3 4)) (mapcon (lambda (tail) (mapcar (lambda (x) (cons (car tail) x)) (cdr tail))) a) ==> ((1 . 2) (1 . 3) (1 . 4) (2 . 3) (2 . 4) (3 . 4)) ...
Your "nothing in the body" is not nothing - it is an empty list (), which is the same as NIL. In Common Lisp, you can use the form values to return any number of values - including zero: * (defun funny (counter ten) (if (< counter ten) (values) (values...
First, note that the standard actually contains functions that will help with things like this. There's a useful count-if function that can take a predicate and count how many elements in a list satisfy it. For your case, you could do: CL-USER> (count-if #'(lambda (x) (> x 5)) (list 1...
You tagged this as both Common Lisp and Racket, which are two completely different languages. If you're using Racket or Scheme and want to return from a function early, you can do it using a continuation: (define (my-function x y) (call-with-current-continuation (lambda (return) (when x (return y)) ;; Rest of...
Perhaps I'm misunderstanding something here, but it seems to me that you want to represent an EBNF as a piece of data. If this is the case, you could simply use an s-expression. Something like this, perhaps? #lang racket (define my-ebnf `((A (a A b)) (Q (z z Q z))...
Once again, there are problems with the parentheses. Also the logic seems off, you should test the second case first: (define (prime? x n) (cond ((= x n) (display "prime")) ((= 0 (remainder x n)) (display "not prime")) (else (prime? x (+ n 1))))) Use it like this, starting n...
Your function application syntax is wrong. Function application is always prefix in Scheme, i.e. car(lst) should be (car lst), etc. Also, (pair? 'lst) is wrong, since you should not be quoting the argument. That will test if the symbol lst is a pair, which is obviously always false. You...
Common Lisp has a powerful macro system. You can make new syntax that behave exactly the way you want them to behave. It's even expressed in it's own language making everything in the language available to transform the code from what you want to write to something that CL actually...
python,shell,lisp,common-lisp,sbcl
Given the file test.py: import sys sys.exit(42) You can run it with sb-ext:run-program and examine the exit code as follows: CL-USER> (sb-ext:run-program "python" '("test.py") :search t :wait t) #<SB-IMPL::PROCESS :EXITED 42> CL-USER> (sb-ext:process-exit-code *) 42 ...
function,recursion,lisp,common-lisp,exponents
Yeah, your function has a slight issue with it: :-) You're recursing into threes instead of cubes. You're trying to call cons with one argument (it requires two). You're not changing the value of lst in the recursion, so, since the base case returns lst, you'll always get the initial...
When you don't have any around methods, the order of method application is: all before methods from most specific to least specific, then the most specific primary method, and then the after methods from least specific to most specific. In your case you have two primary methods (methods without :before...
post,lisp,common-lisp,hunchentoot
Change your handler to this (define-easy-handler (test2 :uri "/test2") (name) (with-html-output-to-string (*standard-output* nil :prologue t :indent t) (:html (:body (:h1 (str name)))))) Then it should work. Read the cl-who documentation. Especially the information on local macros. I am including the relevant documentation here. A form which is neither a string...
IF e1 THEN a ALSO b ALSO c ELSE d ALSO e ALSO f Is just (COND (e1 a b c) (T d e f)) See MLISP from David Canfield Smith, 1970....
You moslty already answered your own question, the difference is as you described. :some-symbol will be in :KEYWORD package, and 'SOME-SYMBOL will be in your current package CL-USER by default. In loop macro it's just a matter of taste. Some people prefer to use :for notation to get better syntax...
tree,lisp,common-lisp,tree-traversal,postorder
I just figured that you have to call tree-depth not postorder. Though the answer basically stays the same: As soon as you use trace to get the call-tree: (trace tree-depth) (tree-depth '(1 (2 (4) (6)) (5 (7) (8)))) 0: (TREE-DEPTH (1 (2 (4) (6)) (5 (7) (8)))) 1: (TREE-DEPTH (2...
EVAL doesn't have access to lexical variables. The CLHS says: Evaluates form in the current dynamic environment and the null lexical environment. If you declare the variable special it will work, since this performs a dynamic binding rather than a lexical binding. (let ((NF 5)) (declare (special NF)) (eval 'NF))...
Lisp macros operate on arguments that have already been read by lisp's reader. Because of that a macro can't change how it's arguments are read, and if you pass an argument that will signal an error when you try to read it, e.g. 9:00 in (test 9:00), the reader signals...
This better formatting should make it easy to spot the error: (defun f (l) (cond ((null l) nil) ((listp (car l)) (append (f (car l))) (f (cdr l) (car (f (car l))))) (t (list (car l))))) If that does not help, use SBCL to compile the function. It will give...
You have a couple of erroneous parentheses, and the base case is wrong (you have to return the accumulator). Try this: (define (rev revs n) (cond ((= n 0) revs) (else (rev (+ (* revs 10) (remainder n 10)) (quotient n 10))))) Remember, in Scheme parentheses mean "function application, if...
clojure,scheme,lisp,common-lisp
The empty product is 1. The reason is that 1 is a neutral element for *. If you have the product of 2 and 3 and then multiply by the product of nothing, you will get 2*3*1 = 6. We can write (product (product 2 3) (product)) = (product 6...
"Lisp" is a family of languages, not a single language. Many languages in the family (e.g., Common Lisp) don't specify the internal representations, but rather the contract that the structures and functions have to preserve. In the case of cons, it's roughly the equations: (car (cons x y)) == x...
define in Scheme is not easily implemented in Common Lisp. It's not easily implemented in Scheme either. It's transformation is different in different scopes: (define test value) ; defines test, value can be anything even (lambda ..) which makes a procedur object (define (test arg ...) body ...) ; defines...
The problem is that if (reverse (cdr lat)) returns a list eg (3 2) then (cons '(3 2) (1)) turns into ((3 2) 1). A classical way to do this would be to make a local procedure that takes an accumulator as well as the argument of the global procedure....
You can use setf and the nth accessor: (defun replace-index (node index new-value) (setf (nth index node) new-value) node) (defparameter *orig* (list 1 2 3 4)) (defparameter *mod* (replace-index *orig* 2 99)) (list *orig* *mod*) ; ==> ((1 2 99 4) (1 2 99 4)) ...
lisp,common-lisp,gnu-common-lisp
(make-hash-table :test #'equal) ...
function,parameters,lisp,common-lisp
I'm not a Common Lisp expert, but I guess the way you are calling greater is wrong. This program works for me: (defun greater (x y) (if (> x y) x y)) (print (greater 5 12)) ...
list,lisp,common-lisp,cons,cdr
In terms of what they do, car and cdr are equivalent to first and rest. This is quite clear in the documentation. The HyperSpec says on the entry for first, second, &c: The functions first, second, third, fourth, fifth, sixth, seventh, eighth, ninth, and tenth access the first, second, third,...
debugging,lisp,common-lisp,sbcl,slime
I had compiled swank with debug set to 3. Because of this, when I would step after the break it would then step into swank, giving the weird behavior described.
functional-programming,lisp,common-lisp
Common Lisp is multi-paradigm, not purely functional. There's really no reason to change your code algorithm from C#. If you want to write in a procedural style, you can continue to do so. (defun main (&rest args) (declare (ignore args)) (loop (princ "Enter the number:") (finish-output) (let ((name (read-line)) (numbers...
The big-bang form works by passing a "state" throughout handlers, which is then handed off to the to-draw handler to paint the picture that will be flushed to the screen. For starters, you should lift your drawing code into big-bang's to-draw clause: (big-bang null (to-draw (λ (state) (text "---Small Shack---"...
I am not a smartparens user but I found the answer from its wiki: You can bind ) to sp-up-sexp command: (define-key smartparens-mode-map ")" #'sp-up-sexp) ...
For defun without parameters, there should be an empty parameter list, like the following: (defun yn () (let ((ht (random 2))) (if (eq ht 1) (princ heads) (princ tails)))) ...
You can use eval: (mapcar #'eval *test*) However, this is a suboptimal solution. You would be much better off saving either a lambda: (defmacro make-model-lambda (args) (list* 'lambda () (apply #'make-model args))) (defparameter *test* (make-model-lambda ....)) (funcall *test*) or just the list of args themselves: (defparameter *test* (mapcar (lambda (name-id)...
(defun discrete (lis) (cond ((and (listp lis) (not (equal lis nil))) (let ((sum 0)) (loop for item in lis do (cond ((or (not (numberp item)) (equal 0 item)) t) ((and (numberp item) (> item 1)) (setf sum (+ 1 sum))) ((and (numberp item) (< item 1)) (setf sum (- sum...
list,recursion,lisp,common-lisp
Your code does not return NIL every time; it works well for simple lists. For instance (deep-find '(A B (C D)) 'A) returns T as it should. You have three cases in your cond: end of list, list head check, and list tail check. However, there is nothing regarding trees...
sockets,tcp,lisp,common-lisp,usocket
I don't think it's printing twice. I think it's printing (via write-line) once, and then write-line is returning the line, and the REPL is printing the return value. E.g., if you modify your mytest to return nil, I think you'll see the output that you're expecting: (defun mytest (command) (let...
Open the file and read in the data: (with-open-file (f "file.txt") (read f)) ...
list,function,recursion,lisp,common-lisp
This problem can be solved using the tortoise and hare algorithm where you have two cursors scanning though tortoise at one cons at a time and hare at double speed starting on the second element. If the tortoise and hare is the same element you have a cycle. (defun cyclicp...
When evaluated, '(nil) and (list nil) produce similar lists, but the former can be considered constant when present in source code. You should not perform any destructive operations on a constant quoted list in Common Lisp. See http://l1sp.org/cl/3.2.2.3 and http://l1sp.org/cl/quote. In particular, the latter says "The consequences are undefined if...
How about using lexical-let to penetrate the lambda? Is the correct answer 100? (defun enumerate-indicies (func) (let ((index 0)) (while (< index 5) (funcall func index) (setq index (1+ index))))) (defun enumerate-multiplied-indicies (func) (lexical-let ((func func)) (enumerate-indicies #'(lambda (index) (funcall func (* 10 index)))))) (defun test/enumerate-multiplied-indicies () (lexical-let ((sum 0))...
clojure,functional-programming,lisp
You are misunderstanding the format of a function definition. In your function, the single argument 'colors' is untyped and can be anything. The square brackets are used to denote the beginning and end of the arguments list (i.e. the symbols for the arguments are wrapped in a vector to distinguish...
append returns the new value, it does not modify its arguments. You need to use setq: (setq temp (append temp (list 1))) or push (which adds to the beginning of the list, not the end!): (push 1 temp) ...
In R, brackets are used to group multiple statements in a "compound statement", which appears to be the role played by progn in Lisp. As with progn, all of the component statements are evaluated, but only the value of the final statement is returned. with(mtcars, {qqnorm(mpg); qqline(mpg)}) ...
emacs,lisp,elisp,evil-mode,paredit
You could just advice paredit-mode: (defadvice paredit-mode (around paredit-disable-evil activate) (if paredit-mode ad-do-it (turn-off-evil-mode) ad-do-it)) Also, did you try lispy? It's my Paredit-like package that's inspired by vi. It has more features than Paredit, like inline-eval, region manipulation and outlines....
You can use the cl-ppcre library for regular expressions. Its regex flavour understands the word boundary \b. The replacement could work like this: (cl-ppcre:regex-replace-all "\\bwa\\b" "ba wa walid" "") => "ba walid" I guess that you want to collapse any whitespace around the removed word into one: (cl-ppcre:regex-replace-all "\\s*\\bwa\\b\\s*" "ba...
Append isn't supposed to modify anything Why doesn't append affect list y? The first sentence of the documentation on append is (emphasis added): append returns a new list that is the concatenation of the copies. No one ever said that append is supposed to modify a list. You can't change...
lambda,macros,lisp,common-lisp,slime
Here's my implementation of the macro that generates the functions you initially listed: (defmacro defchord (name steps) `(defun ,name (foo scale) ,(concatenate 'string "Generates a " (symbol-name name) " on scale-step FOO of scale SCALE") (list ,.(mapcar (lambda (i) `(%part (+ foo ,i) scale)) steps)))) Some examples: > (macroexpand-1 '(defchord...
I won't attempt to answer completely your broader question about the "best practices" of adding scripting. It seems to me that choosing between "hook-based" solution (in which you define hook implementations by name convention and they are automatically recognized) and "explicit api" solution (in which you use functions predefinied in...
That's because append is not a mutating function. It returns a new list with its arguments appended together. By convention in Scheme, functions that perform mutation end with an exclamation mark, such as set!. You can use set! to modify new-list so that it is updated, like this: (set! new-list...
CL-USER 8 > (reduce #'min '((1) (-1) (3)) :key #'first) -1 or CL-USER 9 > (loop for e in '((1) (-1) (3)) minimize (first e)) -1 I fear getting the container element is more difficult: CL-USER 9 > (defun minimum (list predicate key) (when list (let* ((m0 (first list)) (m1...
Your (setf b a) in the second line does what is sometimes called a shallow copy in other languages. That is, b does not become an independent copy of the array a, but rather becomes just another name for the exact same array. As a result, when you modify b,...
In Common Lisp you can print a value using, well, the print procedure: (defvar L '((A B) (C))) (print (car L)) ; same as (print (car '((A B) (C)))) => '(A B) (print (cdr L)) ; same as (print (cdr '((A B) (C)))) => '((C)) ...
You were close - but make sure you understand what is a full-house in the first place, and the correct way to use the boolean connectors in this case. Try this: (define is-full-house? (lambda (listy) (let ((sorted-list (sort listy <=))) (or (and (= (first sorted-list) (second sorted-list) (third sorted-list)) (=...
Common Lisp's keyword parameters have a special syntax that lets you tell whether a parameter was supplied or not. I think you should be able to use this to accomplish what you want. Here is a working example, albeit with a slightly different data representation since I don't have your...
An additional comparison for each iteration and one additional iteration gives you this: CL-USER 2 > (defun foo (n e &aux (z (1+ n))) (loop for i to z unless (= i z) collect i else nconc e)) FOO CL-USER 3 > (foo 4 '(f o o)) (0 1 2...
Note that Lisp is not a single language, but a large family of somewhat similar languages. You seem to have tried out Scheme (repl.it runs BiwaScheme) and ClojureScript. The Scheme spec only defines one argument for quote, so BiwaScheme seems to be wrong in that respect. (quote 1 2 3)...
macros,lisp,common-lisp,backticks
You need another comma before A in the nested backquote, so it expands to the value of the variable outside the outside the outer backquote. And then it needs to be quoted to keep from evaluating that as a variable. So it becomes ,',A (defmacro define-access (F A) (let ((X...
lisp,common-lisp,quicklisp,asdf
System For structuring large system use a system management tool. A 'free' one is ASDF. You would need a system declaration, which lists the parts of you library or application. Typically it goes into an own file. Then you load a system or compile a system. There should be tutorials...
You are working only with one field array. That's okay. But you better copy it when you push it to the fields list variable. Use copy-seq. Alternatively create a new field array once you pushed the old one onto the fields list....