In the awk macro of TXR Lisp, I wanted to provide some of the convenience of the "duck typing" in Awk, whereby a string which looks like a number can be used like one. Instead of supporting such a thing directly (which I consider a computer science flunk job in language design) I came up with a field conversion facility that has a succinct syntax: clear and unobtrusive.
http://www.nongnu.org/txr/txr-manpage.html#N-018CCE37
This demonstrates some of it:
1> (awk (t (fconv i) (prinl f)))
1 2 3 4 5
(1 "2" "3" "4" "5")
nil
2> (awk (t (fconv i : r) (prinl f)))
1 2 3 4 5
(1 2.0 3.0 4.0 5.0)
nil
3> (awk (t (fconv : i : r) (prinl f)))
1 2 3 4 5
(1 2 3 4 5.0)
nil
4> (awk (t (fconv i : r : i) (prinl f)))
1 2 3 4 5
(1 2.0 3.0 4.0 5)
There are more conversion specifiers than just
r and
i. There can be any number in a row before the first colon, in the middle, or after the last colon. Conversions are matched with fields and applied. If a colon occurs, conversions after the colon are repeatedly applied to the remaining fields in cyclic repetition. If two colons occur, conversions after the second colon are applied to the trailing fields. There is intelligent prioritizing when these rules overlap.
There are conversions with a z suffix which treat junk as zero:
8> (awk (t (fconv : iz) (prinl f)))
a b c 1 2 3
(0 0 0 1 2 3)
Without this, you get
nil which will blow up if used as a number -- but you can test for it and handle the situation rather than getting a silent zero:
9> (awk (t (fconv : i) (prinl f)))
a b c 1 2 3
(nil nil nil 1 2 3)
Basically the whole "anything can be used as a number, and junk makes zero" nonsense can be avoided with only a small reduction in code golfing. Textual duck typing is a wrongheaded solution for an ergonomic problem, which sacrifices correctness and clarify of data representation for the sake of absolutely minimizing the program character count.