From 3e24991be80d799ceda5a911184162e50994da95 Mon Sep 17 00:00:00 2001 From: Mike Cifelli Date: Sun, 28 Jan 2018 09:55:23 -0500 Subject: [PATCH] Create a direct access array --- lisp/random/array.lisp | 40 +++++++++++++++++++++++++++++++++------- 1 file changed, 33 insertions(+), 7 deletions(-) diff --git a/lisp/random/array.lisp b/lisp/random/array.lisp index b94a19e..f68942d 100644 --- a/lisp/random/array.lisp +++ b/lisp/random/array.lisp @@ -1,11 +1,37 @@ -(defmacro array (size) - `(let ,(map (lambda (x) (list (fuse 'index x))) (create-indices size)) - (dlambda - (:get (i) (eval (fuse 'index i))) - (:set (i value) (set (fuse 'index i) value))))) +(defmacro array (length) + (let* ((this (gensym)) + (index-prefix (fuse this 'index)) + (indices (create-indices length)) + (index-bindings (map (lambda (i) (list (fuse index-prefix i))) indices))) -(defun create-indices (size) - (create-indices-tail (- size 1) ())) + `(let ,index-bindings + (setq ,this + (dlambda + (:get (i) + (eval (fuse ',index-prefix i))) + + (:set (i value) + (if (< i ,length) + (set (fuse ',index-prefix i) value))) + + (:length () + ,length) + + (t () + ((lambda (indices accumulator) + (if (null? indices) + accumulator + (recur + (rest indices) + (cons + (list (first indices) (call ,this :get (first indices))) + accumulator)))) + (reverse ',indices) + nil))))))) + + +(defun create-indices (length) + (create-indices-tail (- length 1) ())) (defun create-indices-tail (index accumulator) (if (< index 0)