list,lisp,common-lisp,cons,cdr , Difference between CDR, CAR and REST, FIRST and possible implementation?

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


Tag: 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 the difference is.

Could anyone sum this up for me? And how do I eventually implement FIRST/REST using CDR, CAR?


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, fourth, fifth, sixth, seventh, eighth, ninth, and tenth elements of list, respectively. Specifically,

(first list)    ==   (car list)
(second list)   ==   (car (cdr list))
(third list)    ==   (car (cddr list))


first is functionally equivalent to car, second is functionally equivalent to cadr, third is functionally equivalent to caddr, and fourth is functionally equivalent to cadddr.

Now, there is a difference, not in functionality, but in style, when you're using these functions. This is actually called out in the HyperSpec as well, e.g., in the entry on rest:


rest is often preferred stylistically over cdr when the argument is to being subjectively viewed as a list rather than as a cons.

For instance, consider two ways of mapping over structures built from cons cells. In the first, we're mapping over a tree of cons cells, calling some function with each leaf (i.e., non-cons) of the tree. We check whether something is a cons with consp, and if it is, we recurse onto its car and cdr. We combine the results into a new cons cell by calling cons.

(defun map-over-cons (function tree)
  (if (not (consp tree))
      (funcall function tree)
      (cons (map-over-cons function (car tree))
            (map-over-cons function (cdr tree)))))

Alternatively, when we map over a list, we typically check for the terminal condition with endp (or null, but endp emphasizes that we're looking for the end of a list, not just looking for nil), and we call the function on the first of the list and recurse into the rest of the list. While it's pretty common to see the result constructed using cons, there's actually list* that will perform the same task when called with two arguments (in general, it can do a bit more) that emphasizes that a list is being constructed:

(defun map-over-list (function list)
  (if (endp list)
      (list* (funcall function (first list))
             (map-over-list function (rest list)))))

Either of these functions could be written using car, cdr, and cons, or with first, rest, and list*, or any combination of them, but sticking to one or the other helps people that may read the code later (including the original author), and signals the intent of the author.

And how do I eventually implement FIRST/REST using CDR, CAR?

How about:

(defun first (x) (car x))
(defun rest (x) (cdr x))

or possibly even better, if you have symbol-function:

(setf (symbol-function 'first) (symbol-function 'car))
(setf (symbol-function 'rest) (symbol-function 'cdr))


Update list of items in c#

I would like to know if you can suggest me an efficient way to update a list of items in c#. Here is a generic example: If CurrentList is [ {Id: 154, Name: "George", Salary: 10 000} {Id: 233, Name: "Alice", Salary: 10 000}] And NewList is [ {Id: 154,...

Sort List of Numbers according to Custom Number Sequence

Question :A set of numbers will be passed as input. Also the redefined relationship of the digits 0-9 in ascending order will be passed as input. Based on the redefined relationship, the set of numbers must be listed in ascending order. Input Format: The first line will contain the the...

Saving elements of a list as data.frames using R

How can I save each element of a list in a in a separate .RData file? Consider the following example: # Generating a list containing 3 matrices set.seed(1) mylist=list(M1=matrix(LETTERS[sample(1:26,9)],3),M2=matrix(LETTERS[sample(1:26,9)],3),M3=matrix(LETTERS[sample(1:26,9)],3)) mylist[1:2] # $M1 # [,1] [,2] [,3] # [1,] "G" "U" "W" # [2,] "J" "E" "M" # [3,] "N" "S"...

Python 3.4: List to Dictionary

I have a string as follows : ['Total Revenue', 31821000, 30871000, 29904000, 'Cost of Revenue', 16447000, 16106000, 15685000, 'Gross Profit', 15374000, 14765000, 14219000, 'Research Development', 1770000, 1715000, 1634000, 'Selling General and Administrative', 6469000, 6384000, 6102000, 'Non Recurring', '-', '-', '-', 'Others', '-', '-', '-', 'Total Operating Expenses', '-', '-', '-',...

Creating a list of items with different tags + filter

I have prepared an example what I would like to produce: link. I have already looked for something and I have found the way to create a filter but just for one value... In my case I need more values all together combined. So that if I wanted a flat...

why java API prevents us to call add and remove together?

As per Java API- IllegalStateException - if neither next nor previous have been called, or remove or add have been called after the last call to next or previous remove()- Removes from the list the last element that was returned by next() or previous() (optional operation). This call can only...

Python - Using a created list as a parameter

When I run my code it tells me: Type Error: unorderable types: str() < float(). I can't figure out why it won't let me compare these two numbers. The list I am using is defined, and the numbers in it have been redefined as floats, so I'm not sure what...

Sort when values are None or empty strings python

I have a list with dictionaries in which I sort them on different values. I'm doing it with these lines of code: def orderBy(self, col, dir, objlist): if dir == 'asc': sorted_objects = sorted(objlist, key=lambda k: k[col]) else: sorted_objects = sorted(objlist, key=lambda k: k[col], reverse=True) return sorted_objects Now the problem...

Zip with tuples and list

I need to write a code that will return the characters of two strings as a list of tuples. The code should stop when either one of the strings runs out of characters. I know is a simple code but I cannot get to work where it gives me more...

Reduction of list dimensions in Python

I'm trying to assign classes to a list of nodes, and separate all nodes into separate lists based on class tag. For example, if we have the following code: #define number of classes MaxC=5 index=[4 4 5 1 4 1 4 5 4 4 3 1 3 3 1 1]...

group indices of list in list of lists

I am looking for an elegant solution for the following problem. I have a list of ints and I want to create a list of lists where the indices with the same value are grouped together in the order of the occurrences of said list. [2, 0, 1, 1, 3,...

Python 2.7 “list index out of range”

I keep getting "IndexError: list index out of range", the code does fine with things like "s = 'miruxsexxzlbveznyaidekl'" but this particular length makes it throw an error. Can anyone help me understand what I did wrong here, not just give me the answer? (I'd like to not have to...

Easiest way to Add lines wrong a .txt file to a list

At the moment I am opening the .txt file twice, once to get the number of all the lines, second to add a line to a list as much as how much lines there are in the .txt file. Is there an easier/better way to do this? This is my...

Django: Handling several page parameters

I have several possible parameter to process in a page. Assume x0, x1, x2,..., x1000. It seems awkward to get and process them one by one by request.GET.get('x0'), request.GET.get('x1'), ... Any idea to put them in a list, so that they can be processed in a loop....

C++ atomic list container

Probably this is a stupid question and I get downvoted but I'll ask it anyways. I'm playing around with std::atomic but I think I didn't fully understand the concept. I'm wondering why there are no atomic Containers. So I played a Little bit around. First I tried the following: std::atomic<std::list<int>...

How to use Split() method in Android

I have String like this. ex:- String myString = "A=myPage{a1,b1,c1};B=myPage{a2,b2,c2};C=myPage{a3,b3,c3};" I need to put each {_,_,_} part into List. like: If List<String> list = new ArrayList() then, list[0]="a1,b1,c1", list[1]="a2,b2,c2", list[2]="a3,b3,c3" I tried to use split, but I don't know how to apply it into this for getting my result. for...

How can I iterate through nested HTML lists without returning the “youngest” children?

Fiddle: I want to iterate through an HTML nested list that is 3-layers deep. <ul> <li>animals <ul> <li>birds <ul> <li>crow</li> <li>parrot</li> </ul> </li> <li>reptiles</li> </ul> </li> <li>plants</li> <li>bugs</li> </ul> I want it to iterate through the list so that it returns the elements in this order (note, this isn't...

print method for list changes values of items

I have problem with printing list. random_itemst_stac contains list of items (cards). Prints of elements and indexes in for loop works perfect but when I print a whole array there are X set for others items - it's strange. Card class: class Card(object): def __init__(self, r=0): self.__rank=0 self.__hidden= False if...

List of tuples from (a, all b) to (b, all a)

I am starting with a list of tuples (a,all b). I want to end with a list of tuples (b,all a). For example: FROM (a1,[b1,b2,b3]) (a2,[b2]) (a3,[b1,b2]) TO (b1,[a1,a3]) (b2[a1,a2,a3]) (b3,[a1] How do I do this using Python 2? Thank you for your help....

How to use XDocument to get attributes and add them to a List

I am trying to load data from an XML file and add it to a List. The XML file looks like this: and this is my code: public void LoadPayments(List<List<string>> list1, List<List<string>> list2) { try { if (File.Exists(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "RentData.xml"))) { int count = 0; XDocument doc; using (var reader =...

Stopping list selection in Python 2.7

Imagine that I have an order list of tuples: s = [(0,-1), (1,0), (2,-1), (3,0), (4,0), (5,-1), (6,0), (7,-1)] Given a parameter X, I want to select all the tuples that have a first element equal or greater than X up to but not including the first tuple that has...

chunk of data into fixed lengths chunks and then add a space and again add them all as a string

I have got hex values as a85b080040010000. I want it to be as a8 5b 08 00 40 01 00 00. I have done it by using below code. But I have to work with very large data. So I want computed time to be very low. import binascii import...

Create array/list of many objects(initially unknown amount) by tag

I'm currently working on a radar system for my space game, and I am trying to work out how to add gameobjects, by tag, to either a list or array that can then be used in other methods. I can't do this manually because I will be procedurally generating each...

How do I read this list and parse it?

I'm using requests and the output I get from the sites API is a list, I've been stuck trying to parse it to get the data from it. I use r = requests.get(urlas, params=params) r.json() to get the data I want. Here is a snippet of the list [{'relation_type': None,...

How to get a reference of the list inside the list comprehension in Python

In previous Python versions, it was possible to get a reference of the list inside the list comprehension by calling locals()['_[1]']. As it seems not to work anymore, is there another way to get it? For example, in the following code, I would like to use the result of the...

Loop by Object inside another Object in Java

I'm not sure how to ask this in word so here's an example : Building class have a data like this : Map<Season, List<Info>> infosBySeason = new TreeMap<Season, List<Info>>(); What I'd like to do is loop for each Building, print by Season infos. Like : Season 1 : Building 1...

Can I put StreamReaders in a list? Or any other way to read a lot of text files at once?

I have a lot of text files and want to read them all by once, how do I do this? This is my code till now: List<StreamReader> lijst = new List<StreamReader>(); using (StreamReader qwe = new StreamReader("C:\\123.txt")) using (StreamReader qwer = new StreamReader("C:\\1234.txt")) lijst.Add(qwe); lijst.Add(qwer); But I get an ObjectDisposedException(Cannot...

I need to make sure that only certain characters are in a list?

I have this to get input and put it in a list: def start(): move_order=[raw_input("Enter your moves: ").split()] And I only want the characters A, D, S, C, H (it's for a game >_>) to be allowed. I've tried using the regular expressions stuff: if re.match('[ADSCH]+', [move_order]) is False: print...

Grouping 0s and 1s in python

I have an array of zeros and ones like [0,0,0,1,1,1,0,0,0,1,1]. How to write a program to save neighboring 0's and 1's in different arrays. E.g. [0,0,0,1,1,1,0,0,0,1,1] giving [0,0,0],[1,1,1],[0,0,0],[1,1]....

Find a single duplicate in a list of lists Netlogo

I am trying to find a duplicate between the sublists of a list , if I have this list let listA [[-9 2] [-9 1] [-9 0][-9 -1][-9 -2][-9 -3][-9 -4][-8 0][-9 0]] and it is a restriction that this list can have only one sublist that can be repeated...

Implementing a dictionary function to calculate the average of a list

As always, I've attempted this for awhile before I proceed to ask a question on here. I know there are several attempts at answering this, but none really worked for what I needed. Here are the instructions: Implement the following three functions (you should use an appropriate looping construct to...

prolog misunderstanding. Split list into two list with even and odd positions. where is my mistake?

I'm trying to split a list into two other list. List Even with the elemnts in even possition and a List Odd with the others. I've been looking over iinternet a solution, but all seem to me like chinese, i can not understand the process. So this is what i've...

C# 2D Generic List [closed]

I'm working on a talents/skills tree system for my game made with Unity and I've got a class for my 45 talents buttons that looks like this: public class SaveTalentClass { public int talId; public int talCurRank; public int talMaxRank; public SaveTalentClass(int id, int cRank, int mRank) { talId =...

Get element starting with letter from List

I have a list and I want to get the position of the string which starts with specific letter. I am trying this code, but it isn't working. List<String> sp = Arrays.asList(splited); int i2 = sp.indexOf("^w.*$"); ...

Prolog: Summing elements of two lists representing an integer(restrictions inside not regular sum!!)

I was solving a problem: A list is representing an integer say 12345 by L=[12,34,5] each element should be from 0 to 99.The exercise is to write a function (sum) that sums two lists and gives the equivalent list of their sum which is representing the sum of two integers....

For-loop does not go over all objects

Why does this for-loop not go through all items: temp = 0 for br in my_list : temp +=1 #other code here #my list is not used at all, only br is used inside here my_list.remove(br) print temp assert len(my_list) == 0 , "list should be empty" So, assertion fires....

Java Get and then remove from a list

In my code i have a list of instances of a class. And i want to get a attribute of 1 instance which is ArrayList. In this class i have implement getters and setters. So I call listofinstances.get(i).getArrayList().remove(0); in order to remove the 1st item of this list. Is this...

Python regular expression, matching the last word

I've the following problem. I'm looking to find all words in a string that typically looks like so HelloWorldToYou Notice, each word is capitalized as a start followed by the next word and so on. I'm looking to create a list of words from it. So the final expected output...

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

how to insert into python nested list

I want to insert an item into a list inside a list. I'm wondering if someone can show me. list5 = [[], [(1,2,3,4), 2, 5]] print("1. list5", list5) list5.insert(0, (2,5,6,8)) print("2. list5", list5) Output: 1. list5 [[], [(1, 2, 3, 4), 2, 5]] 2. list5 [(2, 5, 6, 8), [],...

ZipList with Scalaz

Suppose I have a list of numbers and list of functions to apply to numbers: val xs: List[Int] = List(1, 2, 3) val fs: List[Int => Int] = List(f1, f2, f3) Now I would like to use an Applicative to apply f1 to 1, f2 to 2, etc. val ys:...

Operand order in Scala List.prepend (::)

Odersky has brilliantly optimized Java syntax, enabling object calls without dots and parenthesis. I.e. instead of list.prepend(item), you now simply write list :: item, which also turns language operators into simple object methods. Here, List defines :: (prepend) operator. However, you normally write it vice-verse in Scala, using item ::...

join two different list by id into one list

I've got two different list of two different objects. Then i got one list of a viewmodel that contains properties from both the objects and i want them to be joined into that list. //Product public string id { get; set; } public string unitMeasurement { get; set; } public...

Why cant I refer to a random index in my 4D list, while I know it exists?

I got a 4D list, and I want where I want to display only the [k][3][j][z], but this isnt working. I checked all the counts and they are all 5+, so 3[4] should work... for (int k = 0; k < lijst4D.Count; k++) { for (int i = 0; i...

Convert only floating point numbers to int in list python

I am trying to turn any floating point number in the list 'codes' to an int. codes = [890.0,'JFR'] codes = [int(c) for c in codes] I am getting the error: ValueError: invalid literal for int() with base 10: 'JFR' What I want the list 'codes' to be is: [890,'JFR']...

Filter list using Boolean array

How can I use boolean array as index to filter a list? For example: >>> l = ['a','b','c'] >>> b = [True,False,False] >>> l[b] The result should be: ['a'] I know numpy support it but want to know how to solve in Python. >>> import numpy as np >>> l...

Python RuntimeError: maximum recursion depth exceeded in cmp

I have a complex data structure that I'm trying to process. Explanation of the data structure: I have a dictionary of classes. The key is a name. The value is a class reference. The class contains two lists of dictionaries. Here's a simple example of my data structure: import scipy.stats...

represent an index inside a list as x,y in python

I have a list which contains 1000 integers. The 1000 integers represent 20X50 elements of dimensional array which I read from a file into the list. I need to walk through the list with an indicator in order to find close elements to each other. I want that my indicator...

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