diff options
-rw-r--r-- | ChangeLog | 8 | ||||
-rw-r--r-- | lib.c | 2 | ||||
-rw-r--r-- | txr.1 | 33 |
3 files changed, 43 insertions, 0 deletions
@@ -1,5 +1,13 @@ 2014-02-05 Kaz Kylheku <kaz@kylheku.com> + * lib.c (generic_funcall): If a cons cell is passed as + one argument to a sequence being used as a function, split it into two + arguments. This is consistent with the DWIM operator behavior. + + * txr.1: Document callable objects. + +2014-02-05 Kaz Kylheku <kaz@kylheku.com> + Allow sequences and hashes to be called as functions. This is already supported in the DWIM operator. @@ -3248,6 +3248,8 @@ val generic_funcall(val fun, val arg[], int nargs) case 0: uw_throw(error_s, lit("call: missing required arguments")); case 1: + if (consp(arg[0])) + return sub(fun, car(arg[0]), cdr(arg[0])); return ref(fun, arg[0]); case 2: return sub(fun, arg[0], arg[1]); @@ -5114,6 +5114,39 @@ characters, which are converted to a character string. The lazy versions of these functions such as mapcar* do not have this behavior; they produce lazy lists. +.SS Callable Objects + +In TXR Lisp, sequences (strings, vectors and lists) and hashes can be used +as functions everywhere, not just with the DWIM brackets. Sequences work +as one or two-argument functions. With a single argument, an element is +selected by position and returned. With two arguments, a range is extracted and +returned. Hashes also work as one or two argument functions, corresponding +to the arguments of the gethash function. + +Moreover, when a sequence is used as a function of one argument, and the +argument is a cons cell rather than an integer, then the call becomes a +two-argument call in which the car and cdr of the cell are passed as separate +arguments. This allows for syntax like (call "abc" 0..1). + +.TP +Example 1: + + (mapcar "abc" '(2 0 1)) -> (#\c #\a #\b) + +Here, mapcar treats the string "abc" as a function of one argument (since there +is one list argument). This function maps the indices 0, 1 and 2 to the +corresponding characters of string "abc". Through this function, the list of +integer indices (2 0 1) is taken to the list of characters (#\c #\a #\b). + +.TP +Example 2: + + (call '(1 2 3 4) 1..3) -> (2 3) + +Here, the shorthand 1 .. 3 denotes (cons 1 3). This is treated just like +(call '(1 2 3 4) 1 3), which performs range extraction: taking a slice +of the list starting at index 1, up to and not including index 3. + .SH CONTROL FLOW AND SEQUENCING When the first element of a compound expression is an operator symbol, |