Dana Vrajitoru
C311 Programming Languages
Lisp Input-Output, Loops
Input Statements
- read - reads a value from a stream specified as argument
and returns the value.
- The value entered can be an elisp expression using any existing
symbols or a constant.
- By default the stream is the standard-input which is the
minibuffer. It can be made to point to a file or another buffer.
- (setq n (read))
reads something from the minibuffer and stores it in n. An
optional parameter can specify the format.
Output Statements
- prin1 - prints the evaluation of the expression and returns
its value.
- print - similar to prin1 but introduces a new
line before and after the printed line.
- princ - similar to prin1 but a string is not
printed in quotes.
- All of them can have a stream parameter. By default this is the
standard-output and translates into the current file where the
expression is evaluated. The parameter can be another buffer or a
file.
- An optional parameter can specify the format.
(prin1 "hello world") ; "hello world""hello world"
(princ "hello world") ; hello world"hello world"
Loop: dotimes
(dotimes (counter limit result)
sequence of expressions)
- Repeats the sequence of expressions for a number of times given by
the limit.
- Counter is a local variable that is initialized to 0 and
incremented at each iteration.
- The expression result is returned at the end of the loop
(optional).
Example
(defun factorial (n)
(let ((f 1))
(dotimes (i n f)
(setq f (* f (+ i 1))))))
(factorial 5) ;-> 120
(factorial 1) ;-> 1
(factorial 0) ;-> 1
Loop: dolist
(dolist (variable list result)
sequence of expressions)
- Executes the sequence of expressions for each member of the list.
- During each iteration, the value of the list element can be found
in the variable.
- At the end of the loop, the value of the result is returned
(optional).
Example
(defun maxl (L)
"Returns the maximum element of a list."
(let ((m nil))
(dolist (x L m)
(if (or (not m) (> x m))
(setq m x)))))
(maxl ()) ;-> nil
(maxl '(3 2 6 54 1)) ;-> 54
(maxl '(1)) ;-> 1