diff --git a/README.md b/README.md index 3331bfd..2507c0f 100644 --- a/README.md +++ b/README.md @@ -163,7 +163,8 @@ quote | `(quote (1 2 3))` | `(1 2 3)` | Return the argument without evaluation. Name | Example | Example result | Description ----- | ------- | -------------- | ----------- debug | `(debug)` | `true` | Toggle debug output. -doc | `(doc +)` | `"Return the sum of all arguments."` | Show description of a built-in function. +doc | `(doc +)` | `"Return the sum of all arguments."` | Show the documentation string for a function. +doc | `(doc myfn "Documentation string.")` | `"Documentation string."` | Set the documentation string for a function. loop | `(loop (fn (a) (do (print a) (coinflip))) "hello ")` | `hello hello hello false` | Call the given function repeatedly in a loop until it returns false. meta | `(meta (env) "name")` | `"root/user"` | Read meta information of an entity. read | `(read "(+ 1 2 3)")` | `(+ 1 2 3)` | Read a string as code and return the expression. diff --git a/mad/fact.mad b/mad/fact.mad index 7f45a63..ae19d4c 100644 --- a/mad/fact.mad +++ b/mad/fact.mad @@ -5,3 +5,7 @@ ;; Apply version (def applyFact (fn (n) (if (< n 2) 1 (apply * (range 1 (inc n)))))) + +;; Add documentation +(doc recFact "Calculate the factor of n recursively.") +(doc applyFact "Calculate the factor of n iteratively using apply.") diff --git a/mad/fib.mad b/mad/fib.mad index 5318a14..bbb0416 100644 --- a/mad/fib.mad +++ b/mad/fib.mad @@ -10,3 +10,7 @@ (def fibListRec (fn (n l) (if (< (len l) n) (fibListRec n (push l (sumOfLast l))) l))) (def fibList (fn (n) (fibListRec n [0 1]))) (def fastFib (fn (n) (sumOfLast (fibList n)))) + +;; Add documentation +(doc slowFib "Return the nth number from the Fibonacci sequence recursively.") +(doc fastFib "Return the nth number from the Fibonacci sequence iteratively.") diff --git a/src/Func.php b/src/Func.php index e8e9fe8..1049d1e 100644 --- a/src/Func.php +++ b/src/Func.php @@ -24,5 +24,10 @@ abstract class Func return $this->doc; } + public function setDoc(?string $val): void + { + $this->doc = $val; + } + abstract public function call(array $args); } diff --git a/src/Lib/Core.php b/src/Lib/Core.php index 94d3349..2307184 100644 --- a/src/Lib/Core.php +++ b/src/Lib/Core.php @@ -43,13 +43,14 @@ class Core implements ILib } )); - $env->set('doc', new CoreFunc('doc', 'Get documentation for a function.', 1, 1, - function ($a) { - if ($a instanceof Func) { + $env->set('doc', new CoreFunc('doc', 'Get or set documentation for a function.', 1, 2, + function (Func $a, ?string $str = null) { + if (func_num_args() == 1) { return $a->getDoc(); + } else { + $a->setDoc($str); + return $str; } - - throw new MadLispException('first argument to doc is not function'); } ));