From 02736718dc2e78f61ef84e44006c0d0c6b4058cf Mon Sep 17 00:00:00 2001 From: Alexander Rosenberg Date: Wed, 24 Sep 2025 05:24:33 -0700 Subject: [PATCH] A buch of sequence functions --- src/kernel.sl | 37 +++++++++++++++++++++++++++++++++++++ src/lisp.c | 12 ++++++++++++ src/lisp.h | 1 + 3 files changed, 50 insertions(+) diff --git a/src/kernel.sl b/src/kernel.sl index c2b6116..3ada365 100644 --- a/src/kernel.sl +++ b/src/kernel.sl @@ -399,3 +399,40 @@ (when (zerop n) (return-from nthtail tail)) (setq n (- n 1)))) + +(defmacro doindex (vars &rest body) + (let ((i '::i)) + (list 'let (list (list i 0)) + (list 'while (list '< i (list 'length (second vars))) + (apply 'list 'let (list (list (first vars) i)) + body) + (list 'setq i (list '+ i 1)))))) + +(defmacro dovector (vars &rest body) + (let ((vec '::vec) + (i '::i) + (vh (head vars))) + (list 'let (list (list vec (second vars))) + (list 'doindex (list i vec) + (if (symbolp vh) + (apply 'list 'let (list (list vh (list 'aref vec i))) + body) + (apply 'list 'let (list (list (first vh) i) + (list (second vh) (list 'aref vec i))) + body)))))) + +(defun foreach (func seq) + (tcase seq + (hash-table (maphash func seq)) + (list + (dolist (elt seq) + (funcall func elt))) + ((or vector string) + (dovector (elt seq) + (funcall func elt))))) + +(defun code-char (code) + (string [code])) + +(defun char-code (str) + (aref str 0)) diff --git a/src/lisp.c b/src/lisp.c index 251d0e9..56f626e 100644 --- a/src/lisp.c +++ b/src/lisp.c @@ -2443,6 +2443,17 @@ DEFUN(hash_table_count, "hash-table-count", (LispVal * table)) { return make_lisp_integer(((LispHashtable *) table)->count); } +DEFUN(maphash, "maphash", (LispVal * func, LispVal *table)) { + HT_FOREACH_VALID_INDEX(table, i) { + LispVal *args = + const_list(true, 2, HASH_KEY(table, i), HASH_VALUE(table, i)); + WITH_CLEANUP(args, { + refcount_unref(Ffuncall(func, args)); // + }); + } + return Qnil; +} + DEFUN(puthash, "puthash", (LispVal * table, LispVal *key, LispVal *value)) { return refcount_ref(puthash(table, key, value)); } @@ -3522,4 +3533,5 @@ static void register_symbols_and_functions(void) { REGISTER_FUNCTION(string, "(val)", ""); REGISTER_FUNCTION(subvector, "(seq &opt start end)", ""); REGISTER_FUNCTION(string_to_vector, "(str)", ""); + REGISTER_FUNCTION(maphash, "(func table)", ""); } diff --git a/src/lisp.h b/src/lisp.h index 3ecbbbb..66c2cdf 100644 --- a/src/lisp.h +++ b/src/lisp.h @@ -516,6 +516,7 @@ DECLARE_FUNCTION(hash_table_p, (LispVal * val)); DECLARE_FUNCTION(make_hash_table, (LispVal * hash_fn, LispVal *eq_fn)); DECLARE_FUNCTION(copy_hash_table, (LispVal * table)); DECLARE_FUNCTION(hash_table_count, (LispVal * table)); +DECLARE_FUNCTION(maphash, (LispVal * func, LispVal *table)); DECLARE_FUNCTION(puthash, (LispVal * table, LispVal *key, LispVal *value)); DECLARE_FUNCTION(gethash, (LispVal * table, LispVal *key, LispVal *def)); DECLARE_FUNCTION(remhash, (LispVal * table, LispVal *key));