ability to set docstrings for functions

This commit is contained in:
Pekka Laiho 2020-12-05 10:39:58 +07:00
parent a96b6faa93
commit 02e5176612
5 changed files with 21 additions and 6 deletions

View File

@ -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.

View File

@ -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.")

View File

@ -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.")

View File

@ -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);
}

View File

@ -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');
}
));