26 May 2004 Leimy   » (Master)

How not to write code with scsh [Scheme Shell]

For the hell of it I decided to write that "content_index" calculator in scsh.

With a lot of help from Riastradh on #scsh I've now got the following:

(let ((read-ls-output (field-reader (infix-splitter (rx (+ " ")) -8))))
 (format #t "~A kilobytes"
 (fold + 0
 (map string->number
   (| (find "." -name "content_index" -print0)
    (xargs "-0" ls -l)
                (record fields) ()
                (#t (format #t "~A~%" (list-ref fields 4))))))))) 1024))(newline))
Which works but is incredibly ugly.

It performs the find as you would expect. Then I use the scsh "awk"-like functionality to filter out the 4th field [size]. run/strings builds a list of strings which I convert to numbers using map with string->number.

To sum the items I call fold with + and 0 [is the identity of addition]. I divide it by 1024 and use the result in a format statement [works like printf for scheme]. The let statement binds me an expression holding the result of field-reader which produces a function. The -8 means that I expect at least 8 records and the rest are seen as the final record. This is for

ls -l
when you have files/directories with spaces.

Nasty eh?

There are better ways...

And here it is:

(format #t "~A kilobytes"
(fold + 0
(map file-info:size 
(map file-info
(run/strings (find "." -name "content_index"))))) 1024)) (newline))

Again... thanks fo Riastradh for teaching me about the REPL.


Latest blog entries     Older blog entries

New Advogato Features

New HTML Parser: The long-awaited libxml2 based HTML parser code is live. It needs further work but already handles most markup better than the original parser.

Keep up with the latest Advogato features by reading the Advogato status blog.

If you're a C programmer with some spare time, take a look at the mod_virgule project page and help us with one of the tasks on the ToDo list!