From 4d2ab06904fd69c0fc7ba3c5237127726ab5c98b Mon Sep 17 00:00:00 2001 From: Kaz Kylheku Date: Sun, 15 Nov 2015 08:13:42 -0800 Subject: Functors: structs callable as functions. * lib.c (generic_funcall): If an object is used as a function, get its lambda method and call that. * txr.1: Document functors. --- lib.c | 3 +++ txr.1 | 30 ++++++++++++++++++++++++++++++ 2 files changed, 33 insertions(+) diff --git a/lib.c b/lib.c index 2771c18d..09e85693 100644 --- a/lib.c +++ b/lib.c @@ -4762,6 +4762,9 @@ val generic_funcall(val fun, struct args *args_in) default: callerror(fun, lit("too many arguments")); } + } else if (structp(fun)) { + fun = method(fun, lambda_s); + break; } /* fallthrough */ default: diff --git a/txr.1 b/txr.1 index 65748eb3..281bc167 100644 --- a/txr.1 +++ b/txr.1 @@ -18150,6 +18150,28 @@ A structure type is associated with a static initialization function which may be used to store initial values into static slots. It is invoked when the type is created. +.NP* Functors + +A structure object can be invoked as a function, if it supports an "anonymous" +method. An anonymous method is one whose name is the +.code lambda +symbol. When arguments are applied to an object +.codn s , +the object and those arguments are passed to the +.code lambda +method. If there is no such method, the call is erroneous. + +That is to say, the following equivalences apply, except that +.code s +is evaluated only once: + +.cblk + (call s args ...) <--> s.(lambda args ...) + + [s args ...] <--> [s.lambda s args ...] + + (mapcar s list) <--> (mapcar (meth s lambda) list) +.cble .coNP Macro @ defstruct .synb @@ -18541,6 +18563,14 @@ are placed into a named .codn name . +A method named +.code lambda +allows a structure to be used as if it were a function. When arguments +are applied to the structure as if it were a function, the +.code lambda +method is invoked with those arguments, with the object itself inserted +into the leftmost argument position. + .coNP Macro @ new .synb .mets (new >> { name | >> ( name << arg *)} >> { slot << init-form }*) -- cgit v1.2.3