Basic tips
- Use
(1+ …)
or (1- …)
instead of (+ … 1)
or (- … 1)
- Symbols can sometimes be used instead of strings:
(display'Foo)
instead of (display"Foo")
(unless(…)…)
is shorter than (when(not(…))…)
- Use
(cdr(command-line))
instead of (command-line-arguments)
do
is an iteration construct:
;; Add all numbers between 1 and 10:
(do ((i 1 (1+ i))
(sum 0 (+ sum i)))
((> i 10) sum) ; if i>10: break and return sum (55)
(display sum)
(newline))
Looping over a list
There are several ways one can loop over a list, perform some operation, and output the results. Here are a few ways one could print all the arguments to a hole in uppercase:
(do((a(cdr(command-line))(cdr a)))((null? a))(printf"~a~n"(string-upcase(car a))))
(for-each(lambda(a)(printf"~a~n"(string-upcase a)))(cdr(command-line)))
(printf"~{~a~n~}"(map(lambda(a)(string-upcase a))(cdr(command-line))))
(andmap(lambda(a)(printf"~a~n"(string-upcase a)))(cdr(command-line)))
(memp(lambda(a)(printf"~a~n"(string-upcase a))#f)(cdr(command-line)))
(printf"~{~a~n~}"(map string-upcase(cdr(command-line))))
(printf"~:@(~{~a~n~}~)"(cdr(command-line)))
Note that andmap
and memp
above cannot be replaced by map
, as map
does not necessarily iterate over its arguments in order.
Splitting a string
The shortest way to split a string on spaces:
(read(open-input-string(format"(~a)"x)))
This yields a list of numbers and symbols, the latter of which can be converted to strings via symbol->string
.
2:1 Packer (written in Ruby)
print '(eval(read(open-input-string(utf8->string(string->utf16"',
"(display 10)".encode('utf-8', 'utf-16be'),
'")))))'