Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add LispArray instances and deep copy #1387

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 49 additions & 1 deletion library/lisparray.lisp
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@
;;;; An interface to Common Lisp rank-1 SIMPLE-ARRAYs.

(coalton-library/utils:defstdlib-package #:coalton-library/lisparray
(:use #:coalton)
(:use
#:coalton
#:coalton-library/classes)
(:local-nicknames
(#:types #:coalton-library/types)
(#:complex #:coalton-library/math/complex))
Expand Down Expand Up @@ -84,6 +86,52 @@ WARNING: The consequences are undefined if an uninitialized element is read befo
(cl:setf (cl:aref v i) x)
Unit))

(inline)
(declare copy (LispArray :t -> LispArray :t))
(define (copy v)
"Make a deep copy of the `LispArray` `v`."
(lisp (LispArray :t) (v)
(cl:copy-seq v)))

(define-instance (types:RuntimeRepr :t => Into (List :t) (LispArray :t))
(inline)
(define (into xs)
(let ((type (types:runtime-repr (types:proxy-inner (types:proxy-of xs)))))
(lisp (LispArray :t) (xs type)
(cl:make-array (cl:length xs) :element-type type :initial-contents xs)))))

(define-instance (Into (LispArray :t) (List :t))
(inline)
(define (into v)
(let ((len (length v)))
(if (== 0 len)
Nil
(let ((%into (fn (xs i)
(if (== 0 i)
(Cons (aref v 0) xs)
(%into (Cons (aref v i) xs) (- i 1))))))
(%into Nil (- len 1)))))))

(define-instance (types:RuntimeRepr :t => Iso (LispArray :t) (List :t)))

(define-instance (Foldable LispArray)
(define (fold f init v)
(let ((len (length v))
(%fold (fn (i acc)
(if (== i len)
acc
(%fold (+ 1 i) (f acc (aref v i)))))))
(%fold 0 init)))

(define (foldr f init v)
(let len = (length v))
(when (== 0 len) (return init))
(let ((%foldr (fn (i acc)
(if (== i 0)
(f (aref v 0) acc)
(%foldr (- i 1) (f (aref v i) acc))))))
(%foldr (- len 1) init))))

(lisp-toplevel ()
(cl:eval-when (:compile-toplevel :load-toplevel)
(cl:defmacro define-lisparray-specialization (coalton-type lisp-type)
Expand Down