2 ms·
I get the point about getting rid of cons. You don't need the actual cons data structure; just the accessor abstraction. In TXR Lisp, I define car and cdr for o
by kazinator 12y ago
I get the point about getting rid of cons. You don't need the actual cons data structure; just the accessor abstraction. In TXR Lisp, I define car and cdr for objects other than conses. They are defined in a way that obeys "nil correctness".
$ txr -p '(list (car "ab") (cdr "ab") (cdr "a"))'
(#\a "b" nil)
Note that the cdr/rest of a one character string isn't the empty string, but nil.
So, with a repeating lazy list and a string, we can do the Vigenère cipher in one line:
$ txr -p '[mapcar (ret `@1@2`) "abcd" "1234"]'
("a1" "b2" "c3" "d4")
The mapcar function was modified only very slightly to make this happen correctly for all inputs: its inputs have to be normalized so they are "nil correct": empty vectors and strings have to be mapped to nil. That case does not occur here.
Watch what happens with mappend:
$ txr -p '[mappend (ret `@1@2`) "abcd" "1234"]'
"a1b2c3d4"
Now that required a bit of more of a hack inside mappend: mappend looks at the type of the leftmost list operand and notices that it is a string. Therefore it accumulates a string.
Wait, mapcar has that hack too!
$ txr -p '[mapcar + "abcd" #(0 1 2 3)]'
"aceg"
It didn't kick in in the first example because the function being mapped did not return characters. It returned strings. Strings are not characters and so they cannot be accumulated to make a string. (But of course they can be appended to make a string, which happened in mappend).