March 2013
2 posts
How do I convert an integer to a list of bits?
Novices sometimes ask how to get a convert an integer to a list of bits, often for the purpose of iterating over the bits somehow. Common Lisp has a rich set of functions for directly accessing the bits of an integer, so constructing an intermediate list of bits is rarely necessary.
Here are a few examples of accessing the bits of an integer.
With integer-length and logbitp to test the bit at a...
February 2013
5 posts
The optional arguments of deftype
deftype can be used to create user-defined types that expand into built-in types. For example:
(deftype octet-vector (length)
`(simple-array (unsigned-byte 8) (,length)))
Given this deftype, in a type context, (octet-vector 32) expands into (simple-array (unsigned-byte 8) (32)), or a one-dimensional octet array of length 32.
Lambda lists for deftype are very similar to lambda lists for...
Trying again with with-simple-restart
I have some code that reads data from a config file. If there’s a problem loading, I’d like the opportunity to fix it, outside of Lisp, and retry loading. It’s easy to do that with with-simple-restart and loop:
(loop
(with-simple-restart (try-again "Try again")
(return
(progn
(setf *config* (load-config-file))))
If any error occurs during load-config-file,...
Semicolon style
The standard explains common semicolon comment style in section 2.4.4.2. Section 2.4.4.2.5 includes this short example showing typical use of one through four semicolons:
;;;; Math Utilities
;;; FIB computes the the Fibonacci function in the traditional
;;; recursive way.
(defun fib (n)
(check-type n integer)
;; At this point we're sure we have an integer argument.
;; Now we can get down...
The tree-walkers of CL
If you need to visit a tree in some way, there are two built-in functions that, while not explicitly designed for the purpose, can walk a tree effectively.
First, subst-if takes a predicate function that is called for each cons and atom in a tree. As long as the predicate returns nil, no substitution will actually take place.
Here’s a simple way to turn it into a function:
(defun walk-tree...