lisp , How do to count the number of elements in a list?


How do to count the number of elements in a list?

Question:

Tag: lisp

So here is my code. It should count the number of elements in a list but instead it prints a zero even though a list contains something.

(defun my-list (listA)
    (setq count 0)
    (loop for i in listA
    if(null i)
        count
    else
    do (setq count(+ count 1))))

Answer:

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 rest of the list plus one. eg. (my-length '(1)) ==> (1+ (my-length '()) ==> (1+ 0) ==> 1

That's it. It works for any length list since (my-length '(1 2 3)) ==> (1+ (1+ (1+ 0))) ==> 3

EDIT

Where is count defined? setq updates an existing binding. Perhaps you should use let to make a local binding. Also in loop you can make variables:

(loop :for count :from 0 
      :for element :in listA
      :finally (return count))

loop actually can count, sum and a whole lot more so this is a better way:

(loop :for element :in listA
      :counting t)

Related:


Need help getting CLisp to read standard input into a list


python,lisp,common-lisp,clisp
I'm working on converting some existing Python code to CLisp just as an exercise ... The program reads a list of numbers and creates mean, min, max and standard deviation from the list. I have the file-based function working: (defun get-file (filename) (with-open-file (stream filename) (loop for line = (read-line...

CAR and CDR in LISP


lisp,clisp,cdr
Suppose there's a LISP list L described by ((A B) (C)) How to print the result of (CAR L) and (CDR L)? (in clisp interpreter) I am able to print these simple statements like (CAR `(A B C)) which gives A. But how do I define the list and CAR...

Difference between CDR, CAR and REST, FIRST and possible implementation?


list,lisp,common-lisp,cons,cdr
I'm learning a little bit about functional programming in LISP and here's what I've bumped into: LISP uses CAR, CDR functions as well as FIRST and REST functions. Both related to lists. From what I've learned so far, there's a difference between these two, but I don't quite see what...

Insertion into a list doesn't reflect outside function whereas deletion does?


list,lisp,common-lisp
I am new to Lisp. Deletion of an item in a list by a function gets reflected outside the function but insertion doesn't. How can I do the same for insertion? For example (defun test (a b) (delete 1 a) (delete 5 b) (append '(5) b) (member '5 b)) (setq...

How to use a parameter in a macro call?


macros,lisp,common-lisp,sbcl
I have defined the following simple macro: (defmacro define-class (class-name) `(defclass ,class-name ()())) And now I want to use it in the following function: (defun create-data (mode) (define-class mode)) After compiling the last function I get the following message, the variable MODE is defined but never used. And when I...

How to move a file in Lisp using rename-file


lisp,common-lisp,pathname
What's the best way to move a file in Lisp in an implementation-independent way? For example I have an image file: (setq oldpath #P"SERVER:PICTURES;TEMP;PHOTO.PNG") and I want to move it out of the TEMP directory into the PICTURES directory. This seems to work: (setq newpath (make-pathname :host (pathname-host oldpath) :directory...

How to create a list of sublists in Lisp without map?


list,recursion,lisp,sublist
I'm trying to make a function that creates a list of all sublists in the given list. What I mean is, when I've got a list: (4 (a g b) g (1 2 3) g (4 5 6)) I want a list: ((a g b) (1 2 3) (4 5...

How to express BNF using Lisp?


lisp,racket,grammar,bnf
I want to express a grammar rule that is written in BNF using Lisp. here is the rule. It is important to note that non-terminals are represented in capital letters and the terminals are represented in small letters: A -> a A b I tried to use the define function...

Understanding “let” expression in LISP


lisp,common-lisp,let
I am extremely new to lisp, had previous experience with functional programming (Haskell, SML). Why is this code returning 14, and not 10 (ie. 1 + 2y + 3 + 1)? (defvar x 1) (defun g (z) (+ x z)) (defun f (y) (+ (g 1) (let ((x (+ y...

Printing ith row jth column value in lisp


arrays,multidimensional-array,lisp,clisp
I am taking input N as number of rows of a 2D matrix in lisp, where each row can have maximum of 5 elements in it. So i make it like this. Now for eachrow as it can have any number of elements between 0 to 5. So I made...

How to use do in lisp?


function,lisp,common-lisp
What I'm trying to do is to write a function that which will restart a game of tic-tac-toe after it ends. What is supposed to happen is that the player will be asked if they want to play another game. If they do, then they click yes and a function...

LISP Easy questio about creating new lists


lisp,common-lisp
A function that receives a list with sublist's M*N and returns the sum of all elements of the sublist's example: (solution '( (1 2 3) (4 5 6) ) ) return: (5 7 9) Sry for the bad english thks =)...

Backquote String Interpolation


macros,lisp,common-lisp
Is it possible to use lisp's macro to do string interpolation? For instance, can I make a macro like this: (defmacro test (a) `",a") So that (test abc) returns "abc" as a string? I could probably cheat by quoting it and turning that quote into a string, but that doesn't...

Common Lisp - Writing a function that detects circular lists


list,function,recursion,lisp,common-lisp
I have an assignment for my CS functional languages class where we must write a function able to detect whether or not a given list is circular at its beginning. The function has to be recursive. Let's name it circular : * (setf list1 '(a b c d)) * (rplacd...

Modify list and return it inside a function in lisp


lisp,elisp,common-lisp
(defun testthis (node index newvalue) (set-nth node index newvalue) node ) I would like to modify the nth element of a list in a function and then returns this list to save the modification performed. How can I do a such function in lisp?...

How do to count the number of elements in a list?


lisp
So here is my code. It should count the number of elements in a list but instead it prints a zero even though a list contains something. (defun my-list (listA) (setq count 0) (loop for i in listA if(null i) count else do (setq count(+ count 1)))) ...

Invalid specialized parameter in method lambda list


lisp,common-lisp
I am trying to write a simple coin flip program in Common Lisp. This is the code I have (defun yn (let ht (random 1) (if (eq ht 1) (princ heads) (princ tails)) ) ) It seems simple enough, but I keep getting the error: "Invalid specialized parameter in method...

Common-LISP debugging (code included)


debugging,lisp,common-lisp
I hope to get a quick fix to my code, which takes in a list of numbers, numberlist, and a threshold and return the number of items in numberlist that are greater than threshold. I just can't figure out what's wrong, and I am not familiar with debugging. I am...

how to change the value of sp-navigate-reindent-after-up in smartparens


emacs,lisp,elisp,parentheses
I want to change the default behavior of smartparens to remove the whitespace before the close delimiter. I mean, when I type ) after (a b c |, I hope the final result is (a b c)|. Here, the | is cursor. I searched the documentation of smartparens, and find...

Why does lisp use gensym and other languages don't?


lisp,common-lisp
Correct me if I'm wrong, but there is nothing like gensym in Java, C, C++, Python, Javascript, or any of the other languages I've used, and I've never seemed to need it. Why is it necessary in Lisp and not in other langauges? For clarification, I'm learning Common Lisp.

EVAL/APPLY: too many arguments given to F


lisp,common-lisp,clisp
Hello why do i get *** - EVAL/APPLY: too many arguments given to F on function call with nested lists parameter. I cannot figure it out, since I passed a simple nested list. (defun f (L) (cond ((NULL l) nil) ((listp (car L)) (append (F(car L))) (F(cdr L) (car (F...

LISP macro fail, crashes slime


lambda,macros,lisp,common-lisp,slime
I am using common lisp with slime in emacs and am trying to define a simple macro. However when I run the macro, the emacs slime buffer becomes unresponsive and my computer quickly becomes unusable. Even after exiting emacs I get error messages at the bash prompt about not being...

Value from binding in LFE interpreter using Erlang


erlang,lisp,lfe
I'd like to use Lisp Flavored Erlang as a scripting extension language for an Erlang application. If you want, in a similar way GNU Emacs is configured and extended via Emacs Lisp. I know that the argument is wide and structured; but in the specific case of this question I'd...

If strings are vectors, why are they immutable?


lisp,common-lisp
if strings are vectors of characters, and a vector's elements can be accessed using elt, and elt is setf-able - then why are strings immutable?

Common Lisp Object System method execution order


lisp,common-lisp,clos
I have the following two classes: (defclass person () ()) (defmethod speak ((s person) string) (format t "-A" string)) (defmethod speak :before ((s person) string) (print "Hello! ")) (defmethod speak :after ((s person) string) (print "Have a nice day!")) (defclass speaker (person) ()) (defmethod speak ((i speaker) string) (print "Bonjour!"))...

SBCL Run Shell Command


python,shell,lisp,common-lisp,sbcl
I've seen Executing a shell command from Common Lisp and its answers, but I'm still not sure whether SBCL provides a way execute shell commands from code. The SBCL Manual does support POSIX, but I was hoping for something a bit more higher level. Specifically, I want to call a...

Emacs + SLIME + SBCL (Windows)


windows,emacs,lisp,sbcl,slime
I'm attempting to get Emacs, Slime and SBCL to work together on a Windows 7 machine. I use Linux typically, so I'm not experienced with the process. The problem is that I get this error when I attempt to start SLIME: Searching for program: permission denied, sbcl Here's my Emacs...

Returning from a function inside when statement


scheme,lisp,racket
All I'm trying to do is use a when statement to return a value :( I want the functionality of: if(x) return y And I'm trying to use: (when (x) y) But the when statement is not evaluating in a way that exits the function and return y. It just...

Get element from list of list in lisp


lisp,elisp,common-lisp
I am a beginner with lisp. I manipulate list of list: ((name1, second) (name2, second2)) The goal of my function is to get the second element of the list that have name as it first node. For example: my list is: ((name1, second1) (name2, second2)) getelement list name1 should return...

Append list from assoc to another list in Scheme


scheme,lisp,r5rs
I'm a bit confused on how to append a list that I've gotten from the assoc procedure into another list, here is what I have: (define new-list (list 'test)) (define source-a (list '(a foo) '(b bar) '(c hello))) (append new-list (assoc 'a source-a)) (display new-list) The output is just (test)...

in clojure, function argument type mismatch


clojure,functional-programming,lisp
clojure, function argument is vector, but it takes a map without problem. (defn flower-colors [colors] (str "The flowers are " (:flower1 colors) " and " (:flower2 colors))) (flower-colors {:flower1 "red" :flower2 "blue"}) ;; -> "The flowers are red and blue" Function flower-colors suppose to take vector type argument, but with...

Mapping function in LISP


recursion,mapping,lisp
I need your help on something. I have a list in input: (1 ((2 3) (4 ((5) (6)))) ((7 8) (9 10)) 11) I want to receive in output the following: ((1 2 3 7 8 11) (1 2 3 9 10 11) (1 4 5 7 8 11) (1...

lisp remove a the content of one list from another list


lisp,common-lisp
I have a list of string like this called F: ("hello word i'am walid" "goodbye madame") => this list contain two elements of string and I have another list call S like this ("word" "madame") => this contain two words now I want to remove the elements of the list...

Appending to the result of a “loop-collect” in Lisp


loops,lisp,common-lisp
Let's say I run the following (loop for i to 4 collect i) Then I get a list (0 1 2 3 4). Now, if I want to append something to the result, I may use rplacd on its last element, but since Lisp lists are linked lists, it's not...

Exceed evaluation depth when forward function in Emacs Lisp


emacs,lisp,elisp
Here is just a simplified code snipped I have not managed to work. I do not understand what is wrong. (defun enumerate-indicies (func) (let ((index 0)) (while (< index 5) (funcall func index) (setq index (1+ index))))) (defun enumerate-multiplied-indicies (func) (enumerate-indicies #'(lambda (index) (funcall func (* 10 index))))) The following...

LISP: read number from user and commpare with array index


functional-programming,lisp,common-lisp
Hello guys I'm new In functional programming Really it is not Clear for me anyone can help me ? My Question just for getting the philosophy of writing on Functional programming language for example how I can write a program in Lisp language for reading the user inputs and compare...

Return items of a list in Lisp


lisp
I have to write a program in Lisp that returns the first item of a list if it contains an even number of elements, and the last if it contains an odd number of elements. I need a little advice on where to start? I don't need whole program.

What's the difference between (list nil) and '(nil) in Lisp? [duplicate]


lisp,common-lisp,literals
This question already has an answer here: Why does this function return a different value every time? 4 answers Unexpected persistence of data [duplicate] 1 answer First of all, let me say I'm a beginner in Lisp. To be honest I have been a beginner for some time now,...

No-argument (and) returns t


clojure,scheme,lisp,common-lisp
Both CL and Scheme define (and) to return t (or #t) with no arguments. I'm trying to understand the rationale for this. My naive assumption is that an empty set is false, and passing in zero arguments feels like passing in nothing that can be true. Edit: clojure follows the...

What does backtick mean in LISP?


lisp,common-lisp,backticks
I have this macro, which rewrites define. If I remove the " ` " backtick it won't work. What is the explanation? (defmacro define ((name &rest r) body) `(defun ,name ,r ,body)) ...

How would I get the min/max of a list using a key


lisp,common-lisp
I currently have a list of objects, each containing a certain attribute. I would like to get the element of the list with the min attribute value. Is there a concise way of doing this? The python equivalent would be something like: min(d, key=d.get) Is there a way of getting...

Not numeric atoms LISP


lisp,common-lisp
I want to ask why this function doesn't work... (defun nenum(ls) (cond ((null ls) nil) ((listp car(ls)) (nenum (rest ls))) ((numberp car(ls)) (nenum (rest ls))) (t (cons (car ls) (nenum (rest ls)))))) Example: (nenum '(l 1 i (b) (5) s -2 p)) --> (l i s p) Thank you!...

Are Lisp lists always implemented as linked lists under the hood?


linked-list,lisp,cpu-cache
Are Lisp lists always implemented as linked lists under the hood? Is this a problem as far as processor caching goes? If so, are there solutions that use more contiguous structures which help caching?...

Scheme full-house poke function


list,scheme,lisp,racket
I'm trying to define a function in Scheme that determines if a five-element list contains a full-house (that is, 3 elements are the same and the other 2 are the same, respectively). I have the outline in my head, although I'm messing up the syntax. I'm using and, let, to...

Common Lisp - Giving &rest Lists as Arguments


arguments,lisp,common-lisp,sbcl
As a result of musings around an exercism problem, I am trying to write a function that takes an input number and an arbitrary length list of divisors to test, along with the expected divisibility (i.e. remainder 0) as a boolean, returning true if all expectations are met (defaulting to...

Char Comparison in Common Lisp


sorting,char,comparison,lisp,common-lisp
How can i compare characters with Common Lisp? I have google it and found out that there are some functions to do the comparison, like char=, char/=, char<, char>, char<=, and char>=. But, i can't use all of the functions just like: (char= 'a 'a) (char< 'a 'b) If i...

How to use FFI:def-call-in in clisp


lisp,common-lisp,ffi,clisp
I have figured out how to make use of shared objects created from C code into Clisp using FFI:def-call-out but I am not able to figure out how to use FFI:Def-call-in. I don't know the process and actually I am confused if clisp will also create some .so file that...

Evaluating Function in Lisp


scheme,lisp
I'm new to Lisp and need help understanding this function and the evaluation of (map length '((a b c) (1 2 3 4 5) (v1 v2 v3 v4 v5 v6)))) The value is (3 5 6) (define (map f list) ; applies function f to each element of list (if...

Basic idea of Lisp Macro


macros,lisp,common-lisp
I try to do a very simple thing in Lisp - to find a way to turn on a global valuable nodebug t and then some of debug format form would be silence. To do that, I found I cannot grasp the difference of the following: (defparameter *nodebug* t) (setf...

Structuring large Lisp applications


lisp,common-lisp,quicklisp,asdf
I am currently trying to wrap my head around packages, systems & co. I now have read Packages, systems, modules, libraries - WTF? a few times, and I think I'm still having difficulties to get it right. If I simply want to split a Lisp source file into two files,...