From ef727cbe0e2369bf13d435c41e87ee4036cb13aa Mon Sep 17 00:00:00 2001 From: Pekka Laiho Date: Sat, 5 Dec 2020 09:02:53 +0700 Subject: [PATCH] add reflection to readme --- README.md | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/README.md b/README.md index 0bd81c8..9e1a89f 100644 --- a/README.md +++ b/README.md @@ -379,6 +379,34 @@ PI | PHP constant `M_PI` \_\_DIR\_\_ | Directory of a file being evaluated using the special form `load`. Otherwise null. \_\_FILE\_\_ | Filename of a file being evaluated using the special form `load`. Otherwise null. +## Reflection + +You can use the `meta` function to retrieve the arguments, body or full code of user-defined functions: + +``` +> (def add (fn (a b) (+ a b))) + +> (meta add "args") +(a b) +> (meta add "body") +(+ a b) +> (meta add "code") +(fn (a b) (+ a b)) +``` + +This allows for some fun tricks. For example, we can retrieve the body of a function and evaluate it as part of another function: + +``` +> (def addOne (fn (n) (+ n 1))) + +> (def addTwo (fn (n) (+ n 2))) + +> (def addBoth (fn (n) (+ (eval (meta addOne "body")) (eval (meta addTwo "body"))))) + +> (addBoth 1) +5 +``` + ## Extending The project is easy to extend because it is trivial to add new functions whether the implementation is defined on the PHP or Lisp side.