lisp , Return items of a list in Lisp

Return items of a list in Lisp


Tag: 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.


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) ;; T

The function first returns the first element of a list.

(first '(a b c)) ;; A

The function last returns the last cons of a list, so you'll have to unwrap the value using FIRST.

(last '(a b c)) ;; (C)
(first (last '(a b c))) ;; C

You could then combine these into a function like so:

(defun get-first-if-even-length (list)
  (if (evenp (length list))
      (first list)
    (first (last list))))

This function returns the first or the last element in the list, depending if its length is even or not.


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

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?...

How to use FFI:def-call-in in 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...

LISP macro fail, crashes 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...

Common Lisp - Giving &rest Lists as Arguments

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...

Modify list and return it inside a function in 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?...

No-argument (and) returns t

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...

Printing ith row jth column value in lisp

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...

Mapping function in 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...

Common Lisp Object System method execution order

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!"))...

Common-LISP debugging (code included)

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...

lisp remove a the content of one list from another list

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...

LISP Easy questio about creating new lists

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

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...

Not numeric atoms 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!...

How to use a parameter in a macro call?

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...

Evaluating Function in 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...

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

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...

Basic idea of Lisp Macro

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...

Exceed evaluation depth when forward function in Emacs Lisp

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...

Invalid specialized parameter in method lambda list

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...

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

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.

How to use do in 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...

What does backtick mean in LISP?

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)) ...

LISP: read number from user and commpare with array index

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...

Scheme full-house poke function

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...

EVAL/APPLY: too many arguments given to F

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...


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...

If strings are vectors, why are they immutable?

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?

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

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...

Return items of a list in 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.

Returning from a function inside when statement

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...

Understanding “let” expression in LISP

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...

Char Comparison in 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...

in clojure, function argument type mismatch

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...

Append list from assoc to another list in Scheme

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)...

Common Lisp - Writing a function that detects circular lists

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...

Need help getting CLisp to read standard input into a list

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...

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

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...

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

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)))) ...

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

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...

SBCL Run Shell Command

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...

Value from binding in LFE interpreter using Erlang

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...

Appending to the result of a “loop-collect” in 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...

How to express BNF using Lisp?

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...

Emacs + SLIME + SBCL (Windows)

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...

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

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,...

How to move a file in Lisp using rename-file

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...

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

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...

Get element from list of list in 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...

Structuring large Lisp applications

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,...