Last active
February 28, 2023 21:35
-
-
Save saikyun/cdb63d77abd5a83b66108a289fd358a6 to your computer and use it in GitHub Desktop.
Copy on write tuples for janet
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(defn push | |
[l v] | |
[;l v]) | |
(defn pop | |
[l] | |
(if (empty? l) | |
l | |
(tuple/slice l 0 -2))) | |
(defn insert | |
[l at & xs] | |
(if (empty? xs) | |
l | |
[;(tuple/slice l 0 at) ;xs ;(tuple/slice l at)])) | |
(defn remove | |
[l at &opt n] | |
(default n 1) | |
[;(tuple/slice l 0 at) ;(tuple/slice l (min (length l) (+ at n)))]) | |
(push [1 2] 3) | |
#=> [1 2 3] | |
(pop [1 2 3]) | |
#=> [1 2] | |
(insert [1 2 3] 2 1337 10) | |
#=> [1 2 1337 10 3] | |
(remove [1 2 3] 0 1) | |
#=> [2 3] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(defn new-list | |
"Creates a struct where a key represents the index of a list." | |
[& xs] | |
(if (empty? xs) | |
{:length 0} | |
(struct :length (length xs) | |
;(array/concat ;(seq [i :range [0 (length xs)] | |
:let [v (in xs i)]] | |
@[i v]))))) | |
(new-list 1 2 3) | |
(defn push | |
[l v] | |
(struct/with-proto l | |
:length (inc (l :length)) | |
(l :length) v)) | |
(var l (new-list)) | |
(for i 0 10000 | |
(set l (push l i))) | |
# seems prototypes only works for 200 layers | |
(get l 9800) #=> 9800 | |
(get l 9799) #=> nil |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment