Sunday, June 21, 2009

Dissecting a masterpiece

Once in a while I've stumble a code that does what I want but I can't understand how it works. The programming language is right, I know all the operators that are used(*) with everything clear and well formed but the composition is way beyond my limits of comprehension. In that case I know that I've encountered a masterpiece. There is two explanations why I can't get it. I'm either lazy or stupid. Usually I try to fix the first before thinking about the second.
Ten days ago I needed a way of slicing arrays so I asked for advice on cll. Denizens provided me with reference to some nice libraries like Tamas Papp affi & xarray and Marco Antoniotti MAKE-ARRAY-SLICE. However it was Pascal J. Bourguignon that pushed my limits. Here's my code cleared a little bit and using a suit object instead of array for easier printing.
My requirement were creating a function slice that will behave as aref with additional functionality of creating a slice for every non integer index.Example:
For foo being 2 dimensional array (2 5)
0 1 2 3 4
5 6 7 8 9

(slice foo 1 2) <=> (aref foo 1 2)
7
However for every subscript that's not an integer:
(slice foo 1 t)
5 6 7 8 9

(slice foo t 4)
4 9

There's two great ideas in his solution:
1st Creation of template functions like make-reader that use non integer indices as arguments while the integer indices are prespecified.
2nd Generation of looping construct in make-copier, make-printer & make-writer. This was the hardest problem for me. My approach was making a variations generator and use it indices supplier to aref but this is far better.

Here's how it is used:
(setf foo (make-instance 'suit :array (make-array '(2 3 4))))
NIL NIL NIL NIL
NIL NIL NIL NIL
NIL NIL NIL NIL

NIL NIL NIL NIL
NIL NIL NIL NIL
NIL NIL NIL NIL
(slice foo 1 t 2)
NIL NIL NIL

(setf (slice foo 1 t 2) 3)
NIL NIL NIL NIL
NIL NIL NIL NIL
NIL NIL NIL NIL

NIL NIL 3 NIL
NIL NIL 3 NIL
NIL NIL 3 NIL

(slice foo 1 t 2)
3 3 3

(*) Actually almost all of them. This is the first time I've encountered GET-SETF-EXPANSION

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.