nth element of a lisp

Discussion of Emacs Lisp

nth element of a lisp

How to define a function that takes a list and n, and returns the nth element of the list, using cdr and car.
sugar

Re: nth element of a lisp

Homework?

CDR returns a list without the first element, right? Calling CDR on the output of CDR returns a list without the first two elements; the third element is at the front of the resulting list... How many times to get the Nth element at the front of the resulting list? CAR...

nuntius

Posts: 532
Joined: Sat Aug 09, 2008 10:44 am
Location: Newton, MA

Re: nth element of a lisp

You would use a recursive function to get the nth element of the list using only CAR and CDR.

Click to find out more about RECURSION.

Click to find out more about the CAR function.

Click to find out more about the CDR function.
omouse

Posts: 3
Joined: Tue Sep 08, 2009 5:08 pm

Re: nth element of a lisp

This is e-lisp, not scheme or common lisp, I really don't expect homework. How about a little less evasion and snarkiness. In e-lisp, use the (nth ...) built-in function.
Christopher Oliver

Posts: 5
Joined: Fri Sep 05, 2008 2:05 pm

Re: nth element of a lisp

Like Cristopher Oliver said, u can use the nth function.

[Function]
nth n list

(nth n list) returns the nth element of list, where the car of the list is the ``zeroth'' element. The argument n must be a non-negative integer. If the length of the list is not greater than n, then the result is (), that is, nil. (This is consistent with the idea that the car and cdr of () are each ().) For example:

(nth 0 '(foo bar gack)) => foo
(nth 1 '(foo bar gack)) => bar
(nth 3 '(foo bar gack)) => ()
Johny22

Posts: 11
Joined: Thu Oct 29, 2009 5:36 am

Re: nth element of a lisp

Which is the best way to delete some element, whose number is known
from a list ? Is it the following ?

(delete-if (lambda (x) t) some-list :start i :count 1)

thanks
Jacey

Posts: 1
Joined: Fri Nov 04, 2011 12:48 am

Return to Emacs Lisp

Who is online

Users browsing this forum: No registered users and 1 guest