emacs lisp tutorial: list & vectors

Fresh from the oven:

=E3=80=88Emacs Lisp Tutorial: List =EF=BC=86 Vector=E3=80=89
http://xahlee.org/emacs/elisp_list_vector.html

(for beginner lisper only)

plain text version follows. heavy use of unicode. also has html
tables.

-------------------------------------------------
Emacs Lisp Tutorial: List =EF=BC=86 Vector

Xah Lee, 2011-02-21

This page is a practical tutorial of Emacs Lisp's list and vector
datatype. If you don't know elisp, first take a look at Emacs Lisp
Basics.

Lisp has vector and list datatypes. These are similar to other
language's list, vector, array.

=E2=94=81=E2=94=81=E2=94=81=E2=94=81=E2=94=81=E2=94=81=E2=94=81=E2=94=81=E2=
=94=81=E2=94=81=E2=94=81=E2=94=81=E2=94=81=E2=94=81=E2=94=81=E2=94=81=E2=94=
=81=E2=94=81=E2=94=81=E2=94=81
Vectors

To create a vector, write it like this (vector a b =E2=80=A6).

If you do not want the elements evaluated, write it like this: [a b
=E2=80=A6].

Creating a vector:

;; creating a vector
(setq v (vector 3 4 5)) ; each element will be evaluated
(setq v [3 4 5]) ; each element will NOT be evaluated

Length:

(length (vector 3 4 5))

Getting a Element:

use =E2=80=9Celt=E2=80=9D.

(elt (vector 3 4 5) 0) ; =E2=87=92 3. index starts at 0

Changing a Element:

use =E2=80=9Caset=E2=80=9D.

(setq v [3 4 5])
(aset v 0 "b")
v  ; =E2=87=92 ["b" 4 5]

=E2=94=80=E2=94=80=E2=94=80=E2=94=80=E2=94=80=E2=94=80=E2=94=80=E2=94=80=E2=
=94=80=E2=94=80=E2=94=80=E2=94=80=E2=94=80=E2=94=80=E2=94=80
Nested Vector

;; nested vector
[[1 2] [3 4]] ; 2 by 2 matrix
[8 [3 [2 9] c] 7 [4 "b"]] ; random nested vector


=E2=94=80=E2=94=80=E2=94=80=E2=94=80=E2=94=80=E2=94=80=E2=94=80=E2=94=80=E2=
=94=80=E2=94=80=E2=94=80=E2=94=80=E2=94=80=E2=94=80=E2=94=80
Looping Thru Vector

One simple way to go thru a vector is using mapcar. Note that it
returns a list, not vector.

;; add 1 to each
(mapcar '1+ [3 4 5] ) ; =E2=87=92 (4 5 6)

;; get first element of each row
(mapcar (lambda (x) (elt x 0)) [[1 2] [3 4]] ) ; =E2=87=92 (1 3)

You can also use =E2=80=9Cwhile=E2=80=9D. Example:

(setq v [3 4 5])
(setq i 0)
(while (< i (length v))
  (insert (format "%i" (elt v i)))
  (setq i (1+ i))  ) ; inserts "345"


=E2=94=80=E2=94=80=E2=94=80=E2=94=80=E2=94=80=E2=94=80=E2=94=80=E2=94=80=E2=
=94=80=E2=94=80=E2=94=80=E2=94=80=E2=94=80=E2=94=80=E2=94=80
Join and Misc

You can join 2 vectors into a new vector by =E2=80=9Cvconcat=E2=80=9D. You =
can convert
a vector to list by =E2=80=9Cappend=E2=80=9D, e.g. (append myVector nil).
(info "(elisp) Vector Functions")

=E2=94=81=E2=94=81=E2=94=81=E2=94=81=E2=94=81=E2=94=81=E2=94=81=E2=94=81=E2=
=94=81=E2=94=81=E2=94=81=E2=94=81=E2=94=81=E2=94=81=E2=94=81=E2=94=81=E2=94=
=81=E2=94=81=E2=94=81=E2=94=81
List

To create a list, write it like this (list a b =E2=80=A6).

If you do not want the elements evaluated, write it like this: '(a b
=E2=80=A6).

; prints a list
(message "%S" '(a b c))

; assign a list to a var
(setq mylist '(a b c))

; create a list of values of variables
(let ((x 3) (y 4) (z 5))
  (message "%S" (list x y z))
) ; prints "(3 4 5)"

Some List Element Extraction Functions Function	Purpose
(car mylist)	first element
(nth n mylist)	nth element (start from 0)
(car (last mylist))	last element
(cdr mylist)	2nd to last elements
(nthcdr n mylist)	nth to last elements
(butlast mylist n)	without the last n elements

Here's some example of lists and element extraction.

(car (list "a" "b" "c") )   ; =E2=87=92 "a"
(nth 1 (list "a" "b" "c") ) ; =E2=87=92 "b"
(car (last (list "a" "b" "c")) )   ; =E2=87=92 "c"

(cdr (list "a" "b" "c") )   ; =E2=87=92 ("b" "c")

Basic List Functions Function	Purpose
(length mylist)	number of elements
(cons x mylist)	add x to front
(append mylist1 mylist2)	join two lists

Examples:

(length (list "a" "b" "c") ) ; =E2=87=92 3

(cons "a" (list "c" "d") ) ; =E2=87=92 ("a" "c" "d")
(cons (list "a" "b") (list "c" "d") ) ; =E2=87=92 (("a" "b") "c" "d")

(append (list "a" "b") (list "c" "d") ) ; =E2=87=92 ("a" "b" "c" "d")

Functions that modify a list variable Function	Purpose
(pop mylist)	Remove first element from the variable. Returns the
removed element.
(nbutlast mylist n)	Remove last n elements from the variable. Returns
the new value of the variable.
(setcar mylist x)	replaces the first element in mylist with x. Returns
x.
(setcdr mylist x)	replaces the rest of elements in mylist with x.
Returns x.

The weird names =E2=80=9Ccar=E2=80=9D, =E2=80=9Ccdr=E2=80=9D, and =E2=80=9C=
cons=E2=80=9D are like that for historical
reasons.

(info "(elisp) Lists")

=E2=94=80=E2=94=80=E2=94=80=E2=94=80=E2=94=80=E2=94=80=E2=94=80=E2=94=80=E2=
=94=80=E2=94=80=E2=94=80=E2=94=80=E2=94=80=E2=94=80=E2=94=80
Looping Thru a List

Here's a typical way of going thru a list. It is done with =E2=80=9Cmapcar=
=E2=80=9D.

; add one to each list member
(mapcar (lambda (x) (+ x 1)) (list 1 2 3 4)) ; =E2=87=92 (2 3 4 5)

; add one to each list member using the build in function 1+
(mapcar '1+ (list 1 2 3 4)) ; =E2=87=92 (2 3 4 5)

; take the 1st element of each element in the list
(mapcar 'car  '((1 2) (3 4) (5 6))) ; =E2=87=92 (1 3 5)
(mapcar 'car  '((1 2) (3 4) (5 6))) ; =E2=87=92 (1 3 5)

; take the 2nd element of each element in the ilst
(mapcar (lambda (x) (nth 1 x))  '((1 2) (3 4) (5 6))) ; =E2=87=92 (2 4 6)

; apply a file processing function to a list of files
(mapcar 'my-update-html-footer
        (list
"/home/vicky/web/3d/viz.html"
"/home/vicky/web/3d/viz2.html"
"/home/vicky/web/dinju/Khajuraho.html"
"/home/vicky/web/dinju/Khajuraho2.html"
"/home/vicky/web/dinju/Khajuraho3.html"
        )
)

The =E2=80=9Clambda=E2=80=9D above pretty much means =E2=80=9Csubroutine=E2=
=80=9D. It essentially let
you define a function in the middle of your code. The form is (lambda
arguments body). For example, (lambda (x y) (+ x y)) would be a
function that takes two arguments, x and y, and returns their sum.
Loop thru List with =E2=80=9Cwhile=E2=80=9D

Another common form to loop thru a list is using the =E2=80=9Cwhile=E2=80=
=9D function.
In each iteration, =E2=80=9Cpop=E2=80=9D is used to reduce the list. Here's=
 a example
of going thru a list using the =E2=80=9Cwhile=E2=80=9D function.

(let (mylist)
  (setq mylist '(a b c))
  (while mylist
     (message "%s" (pop mylist))
     (sleep-for 1)
  )
)

Following is another example of using =E2=80=9Cwhile=E2=80=9D to loop thru =
a list.

; pop head of mylist
; prepend it to mylist2
; resulting a reversed list
(let (mylist mylist2)
  (setq mylist '(a b c))
  (setq mylist2 '())
  (while mylist
    (setq mylist2
          (cons (pop mylist) mylist2)
    )
  )
  mylist2
)

First, use =E2=80=9Clet=E2=80=9D to set a code block, with temporary variab=
les
=E2=80=9Cmylist=E2=80=9D and =E2=80=9Cmylist2=E2=80=9D. =E2=80=9Cmylist=E2=
=80=9D is then set to '(a b c). =E2=80=9Cmylist2=E2=80=9D is
set to a empty list. Then, in the body of =E2=80=9Cwhile=E2=80=9D, the (pop=
 mylist)
drops mylist's first element and returns it, the (cons (pop mylist)
mylist2) creates a list with the new element prepended to =E2=80=9Cmylist2=
=E2=80=9D.
(Note: This code is to illustrate going thru a list. If you want to
reverse a list, use the =E2=80=9Creverse=E2=80=9D function.)

=E2=94=81=E2=94=81=E2=94=81=E2=94=81=E2=94=81=E2=94=81=E2=94=81=E2=94=81=E2=
=94=81=E2=94=81=E2=94=81=E2=94=81=E2=94=81=E2=94=81=E2=94=81=E2=94=81=E2=94=
=81=E2=94=81=E2=94=81=E2=94=81
List vs Vector

Lisp's =E2=80=9Clist=E2=80=9D and =E2=80=9Cvector=E2=80=9D datatypes are al=
so called =E2=80=9Csequences=E2=80=9D. Many
functions, such as =E2=80=9Celt=E2=80=9D, =E2=80=9Cmapcar=E2=80=9D, work on=
 any sequence type. Here's
their primary differences:

    * vector has constant time access to any element.
    * It takes proportionally longer time to access a long list.
    * list's length can grow by pre-pending with =E2=80=9Ccons=E2=80=9D and=
 is fast.
=E2=80=9Cvector=E2=80=9D's length cannot change.

You can nest list and vectors in any way. Example:

;; arbitrary nested list or vector
[ '(3 4) '(5 8) [4 2]]
(list [8 7] '(4 1))

(info "(elisp) Sequences Arrays Vectors")

 Xah =E2=88=91 http://xahlee.org/
0
Xah
2/21/2011 10:11:27 PM
comp.emacs 4800 articles. 0 followers. Post Follow

0 Replies
757 Views

Similar Articles

[PageSpeed] 19
Reply:
Similar Artilces:

Tutorial for server programming in concurrent Haskell
I've recently started a small tutorial for server programming in concurrent Haskell. http://kyagrd.dyndns.org/wiki/HaskellServerProgramming For newbies in Haskell and/or server programming, there should be an introductory tutorial with concrete and simple examples before Simon Marlow's papers about web server implementation in Haskell. This tutorial consists of two famous examples, Echo and Chat, with the source code and makefile to be downloaded, compliled and tested right away. I hope this could be some helpt to those who want to start server programming in Haskell. Server progr...

<Vector> layout in memory
How do vectors 'look' in memory? Are they the same as arrays? Specifically, I have a complex vector container and I wish to pass it to a complex8_t array. The complex vector contains the same struct element as the complex8_t. Can i substitue (cast) pointers from the vector type to complex8_t and get the same, correct results? Isaac Isaac Gerg wrote: > How do vectors 'look' in memory? Are they the same as arrays? > > Specifically, I have a complex vector container and I wish to pass it > to a complex8_t array. The complex vector contains the same struct...

ANT like tool written in Lisp
Hello everybody, I would like to know if there is a tool similar to ANT written in Lisp. I have done some search over the Internet but have no luck so far. Thanks, Serhiy Y ysv_ <syakovyn@gmail.com> writes: > I would like to know if there is a tool similar to ANT written in > Lisp. I have done some search over the Internet but have no luck so > far. There are several. The most popular nowadays is ASDF (version 2). -- __Pascal Bourguignon__ http://www.informatimago.com/ On 8/25/2010 5:28 PM, Pascal J. Bourguignon wrote: > ysv_<...

Setting background and foreground colors for start-up in emacs
Hi everyone, I'm running GNU emacs 21.3.1 on Windows XP. How can I set the configuration for foreground and background colors so it takes effect each time I start emacs from the Desktop shortcut? I know I can give command line args "-fg <color> -bg <color>" if I start it from a Cygwin bash shell, but I'm trying to avoid doing this every time. I want to set it once and have it take effect each time I start emacs either from the shortcut or from the command line. Is there a customization menu for this (from the Options -> Customize Emacs menu?). Or, how do ...

[9fans] inferno-list
Sorry for posting here, but I can't reach you inferno guys. I don't know whether it could be gmail's faults, tell me if I can help in any way. ---------- Forwarded message ---------- From: Mail Delivery Subsystem <mailer-daemon@googlemail.com> Date: Tue, Aug 25, 2009 at 12:18 AM Subject: Delivery Status Notification (Failure) To: 23hiro@gmail.com This is an automatically generated Delivery Status Notification Delivery to the following recipient failed permanently: inferno-list@vitanuova.com Technical details of permanent failure: Google tried to deliver your messag...

New location for Helsinki Lisp meetings
The monthly Helsinki Lisp meetings have been moved to William K (Annankatu 3). The time and date remain unchanged (first thursday of each month, at about 1900). -- Juho Snellman "Premature profiling is the root of all evil." ...

Need Updated List of DB2 CLI PATCH2 Keyword Values
Does anyone no where I can get the latest, up-to-date list of valid values for the CLI PATCH2 keyword? I followed the current link in the on-line DB2 UDB Information Center and it led me to PATCH2 information that was last updated on 21 Nov. 2002. I know for a fact that additional values have been added to this keyword since then because I have seen several references to new values in the description text of various Fixpack APARs. For example, the DB2 support article at: http://www-1.ibm.com/support/docview.wss?rs=71&context=SSEPGG&q1=IY51207&uid=swg21173120&loc=en...

Vector CANcardX and LabView
Anyone had luck with using the Vector CANTech example using their CANCardX? This is high speed CAN (Controller Area Network) used primarily in automotive... Thanks, Chris Chris, I've recently used the Vector CAN-AC2-PCI cards for an automotive application and have modified the Vector supplied LabView drivers, VLabLib.llb to simplify the usage from within LabView 7. Vector's technical support was very responsive in helping to overcome some of my problems dealing with the vcanap.sys driver and may be helpful for your problem. Please provide more specifics to the problem you're ...

subclassing list
Hi, I want to subclass "list". The documentation states to prefer subclassing list instead of UserList. How to you clear the contents of a list subclass without creating a new object? Thanks in advance Uwe class newList(list): def clear(self): self[:] = [] is one way. HTH Regards, Fuzzy http://www.voidspace.org.uk/python/index.shtml [Uwe] > How [do] you clear the contents of a list subclass > without creating a new object? Use the paranoia emoticon: "del x[:]". For example: >>> class L(list): .... pass .... >>> x = L() >>> x.a...

Passing a vector in place of a list of scalars
Is there a generally accepted way to write a function that will accept a vector (or matrix) in place of a list of scalars (or vectors,) without resorting to a series of 'if' statements? For instance if A is a matrix and v = [m n] then the calls repmat(A,m,n) and repmat(A,v) return the same thing. I know about varargin/varargout, but they don't seem to do what I want. "Justin Abbott" <jj_abbott@yahoo.com> wrote in message news:eed0296.-1@webx.raydaftYaTP... > Is there a generally accepted way to write a function that will > accept a vector (or matrix...

debugging in emacs
Hi python users I am using emacs and python-mode.el under dabian testing. is there a way to debug python code where I can step over each line and watch the value of all the variables and be able to change any during debugging. say you have a loop structure and want to see what the values of your variables are during debugging when your code is running as you step line by line. thanks Gary Wessle <phddas@yahoo.com> writes: > Hi python users > > I am using emacs and python-mode.el under dabian testing. > is there a way to debug python code where I can step over each line &...

Re: Changing a list with the information of other
On 7/2/13 at 12:46 AM, jen@fct.unl.pt (Joaquim Nogueira) wrote: >I have the following (possibly very simple) problem. I have a list, >created using a Table >{{0, 1}, {1, w}, {2, 1 + w}, {3, 1 + 2 w}, {4, 2}, {5, 2 w}, {6, 2 + >2 w}, {7, 2 + w}}. >Then, using another Table, I created the list >{1, 1 + w, 2 + w, 2 w, 2, 2 + 2 w, 1 + 2 w, w} >Note that all these elements appear always in second place, in the >ordered pairs of the first list. What I want is an instruction that >allows to replace all these elements by the ones that appear first >in ...

Need help with list of fractions
Hi- I have a list of floats. The list will always be 2^x+1 values, sorted, between 0 and 1. The smallest list would be [0, 0.5, 1]. I need a function that can get a list of any length, and return a new list. For example: >>> foo([0, 1/2.0, 1]) [0, 1/3.0, 2/3.0, 1] >>> foo([0, 1/4.0, 1/2.0, 3/4.0, 1]) [0, 1/5.0, 2/5.0, 3/5.0, 4/5.0, 1] The output list will have 1 more element than the input list. I can't (be bothered to) figure out how foo should work internally. Maybe somebody can help? This stuff is not my strong suit. ...

should we prefer deque over vector
after reading http://www.codeproject.com/vcpp/stl/vector_vs_deque.asp, i realize that deque has its own speed advantage over vector in all the aspect (except for memory deallocation). does it mean that we should prefer deque over vector? (in contrast with c++ standard, which recommence vector over deque) thanks! yancheng.cheok@gmail.com wrote: > after reading http://www.codeproject.com/vcpp/stl/vector_vs_deque.asp, > > i realize that deque has its own speed advantage over vector in all the > aspect (except for memory deallocation). does it mean that we should > prefer deque...

direct parallel port access from Lisp (x86, Linux, CLISP or CMUCL)
I am accessing a relay board attached to a Linux x86 box using CLISP. The relay board has 8 relays. Each relay is controlled by one of the 8 data bits on the parallel port. Lisp calls a small executable (named 'simpleparport', written in C). For example, to turn 4 relays on and 4 off: (shell (format nil "./simpleparport ~D ~D" #x378 #xA5)) To to turn on the bit0 relay and then off again: (shell (format nil "./simpleparport ~D ~D" #x378 1)) (shell (format nil "./simpleparport ~D ~D" #x378 0)) I wonder if I am doing it the hard way. Is the...

Command to find unique entries in a list
Hi, Whats the tcl command to get the unique entries in a list Ex: list: green blue green blue to get the unique entries -- green, blue We have uniq in Unix, The equivalent for uniq in TCL? Please let me know Thanks On Mon, 20 Apr 2009 07:46:14 -0700 (PDT), wrote: > Whats the tcl command to get the unique entries in a list lsort -unique ??? -- Jonathan Bromley, Consultant DOULOS - Developing Design Know-how VHDL * Verilog * SystemC * e * Perl * Tcl/Tk * Project Services Doulos Ltd., 22 Market Place, Ringwood, BH24 1AW, UK jonathan...

FAQ 4.42 How can I tell whether a certain element is contained in a list or array? #17
This is an excerpt from the latest version perlfaq4.pod, which comes with the standard Perl distribution. These postings aim to reduce the number of repeated questions as well as allow the community to review and update the answers. The latest version of the complete perlfaq is at http://faq.perl.org . -------------------------------------------------------------------- 4.42: How can I tell whether a certain element is contained in a list or array? (portions of this answer contributed by Anno Siegel and brian d foy) Hearing the word "in" is an *in*dication that you proba...

NYC LOCAL: Tuesday 9 May 2006 Lisp NYC: Peter Seibel presents Practical Common Lisp
<blockquote what="official Lisp NYC announcement"> From: Heow Eide-Goodman <lists@alphageeksinc.com> Date: 03 May 2006 23:29:01 -0400 Subject: [Lisp] Reminder: Lisp Meeting, May 9th 7:00 at Trinity Please join us for our next meeting on Tuesday, May 9th from 7:00 to 9:00 at Trinity Lutheran Church. Peter Seibel presents: "Practical Common Lisp" "Should we vacation in Bali or Monaco?" ....is the query put forth to Miss September. "Well Peter," she says with perfect lips "Bali has better food, but Monaco has th...

lisp
Hi again Was trying to explain to my friend why Lisp so good. So Lisp, functional and bottom-up programming: I explained this to my friend How many ways to arrange a number of objects: 2 objects? a:b or b:a -> 2 3 objects? a:b:c a:c:b b:a:c b:c:a c:a:b c:b:a -> 6 4 objects? ...messy 20 objects? ...! So if a lisp function does one thing and returns one output every "nugget" can be tested when written because the permutations are manageable - whereas screeds of "standard" code offer vast permutations making bugginess and code management (including non-reusabil...

Distribution Lists
A few questions about distribution lists in PMail 4.21c: 1. How can I drag/drop entries from an address book to a distribution list? The problem I'm having is that I can't get an address book window and a distribution list window both open at the same time. 2. How can I print a list of the entries in a distribution list? There is no print option on the distribution list window and the print button on the main toolbar doesn't do anything when a distribution list window is open. Peter -- **Remove Xs to reply by e-mail** Peter wrote on 26 feb 2005 in comp.mail...

How to make emacs full screen on gnome?
I'm running Fedora with gnome. I spend 99% of my life in emacs though, so it's annoying to give up screen real estate for the gnome menu bars at the top and bottom of the screen. Also the emacs title bar and menu bar are kind of annoying. I don't want to kill these displays for good, but it would be nice to push a key and have the entire screen filled with the business part of my emacs window. (I tried leaving X and doing this in the way terminal mode, but then the resolution is only VGA of course.) Any ideas? Thanks. "foxx" <charlesfox357@hotmail.com> wro...

tutorials #2
tutorials textbooks,ebooks,seminar topics,seminars,visit http://tutorialweb.50webs.com/ tutorial text books * Applied Cryptograph * VB Script text boo * java script text book * CGI Programming text book http://tutorialweb.50webs.com/ * java text book * Programmer's Guide Nokia WAP Server API 1 * aptitude questions (48 pages) * HR Interview Questions http://tutorialweb.50webs.com/ http://tutorialweb.50webs.com/ Seminar topics 1. BLUETOOTH BASED SMART SENSOR NETWORKS(5 pages) 2. BORDER SECURITY USING WIRELESS INTEGRATED NETWORK SENSORS (WINS) (5 pa...

List-directed input, with no <CR> on last record
(sorry if this question appears twice) Suppose one has this program: program test integer :: i open (unit=1, file='data.txt') read (1,*) i write *, i end program test and the file data.txt looks like this: 1 with *no* line feed character at the end. Or maybe I mean no end-of-line character or no <CR>. What I mean is, say, one uses the Notepad editor and just enters "1", or even "1 " without anything else. In this situation, Absoft Pro Fortran 7.0 reports: ? FORTRAN Runtime Error: ? Attempt to read past end of file ...

Support vector machines and MatLAB
Appreciate if someone could tell me how to use Support Vector Machine SVM in MATLAB(6p5). Thanks A starter page... http://www.models.kvl.dk/research/svm_starter/index.asp BR Anders "Trinh Dinh Toan" <pa0115758a@ntu.edu.sg> skrev i meddelandet news:eefe436.-1@webx.raydaftYaTP... > Appreciate if someone could tell me how to use Support Vector Machine > SVM in MATLAB(6p5). Thanks ...

FAQ 3.12 Where can I get perl-mode for emacs? #10
This is an excerpt from the latest version perlfaq3.pod, which comes with the standard Perl distribution. These postings aim to reduce the number of repeated questions as well as allow the community to review and update the answers. The latest version of the complete perlfaq is at http://faq.perl.org . -------------------------------------------------------------------- 3.12: Where can I get perl-mode for emacs? Since Emacs version 19 patchlevel 22 or so, there have been both a perl-mode.el and support for the Perl debugger built in. These should come with the standard Emacs 19...