Adds StaticArray reverse!

This commit is contained in:
Tim Dévé 2020-05-03 15:35:33 +01:00
parent b5d363c85e
commit 5965b098bb
3 changed files with 52 additions and 14 deletions

View File

@ -1,5 +1,21 @@
(defmodule StaticArray
(doc map! "Maps a function over the static array `xs`, mutating it in place. The difference to Array.endo-map (which does the same thing internally) is that this function takes a ref (since you can never have static arrays as values) and that it returns ().")
(defn map! [xs f]
(for [i 0 (StaticArray.length xs)]
(StaticArray.aset! xs i (~f (StaticArray.unsafe-nth xs i)))))
(doc reverse! "Reverse array in place.")
(defn reverse! [a]
(let-do [i 0
j (Int.dec (length a))]
(while (Int.< i j)
(let-do [tmp @(unsafe-nth a i)]
(aset! a i @(unsafe-nth a j))
(set! i (Int.inc i))
(aset! a j tmp)
(set! j (Int.dec j))))))
;; NOTE: Following function declarations are copy of the ones in Array
;; could we share inmplementation between Array and StaticArray?
(defndynamic foreach-internal [var xs expr]
@ -15,11 +31,6 @@
(defmacro foreach [binding expr]
(StaticArray.foreach-internal (car binding) (cadr binding) expr))
(doc map! "Maps a function over the static array `xs`, mutating it in place. The difference to Array.endo-map (which does the same thing internally) is that this function takes a ref (since you can never have static arrays as values) and that it returns ().")
(defn map! [xs f]
(for [i 0 (StaticArray.length xs)]
(StaticArray.aset! xs i (~f (StaticArray.unsafe-nth xs i)))))
(defn reduce [f x xs]
(let [total x]
(do

View File

@ -499,6 +499,26 @@
</p>
</div>
<div class="binder">
<a class="anchor" href="#reverse!">
<h3 id="reverse!">
reverse!
</h3>
</a>
<div class="description">
defn
</div>
<p class="sig">
(λ [(Ref (StaticArray a) b)] ())
</p>
<pre class="args">
(reverse! a)
</pre>
<p class="doc">
<p>Reverse array in place.</p>
</p>
</div>
<div class="binder">
<a class="anchor" href="#str">
<h3 id="str">

View File

@ -4,6 +4,22 @@
(deftest test
(assert-equal test
$[2 4 8]
(let-do [arr $[1 2 4]]
(map!
arr
&(fn [val] (* @val 2)))
arr)
"map! works as expected")
(assert-equal test
$[3 2 1]
(let-do [arr $[1 2 3]]
(reverse! arr)
arr)
"reverse! works as expected")
(assert-true test
(= $[1 2 3] $[1 2 3])
"= works as expected I")
@ -40,15 +56,6 @@
arr))
"reduce works as expected")
(assert-equal test
$[2 4 8]
(let-do [arr $[1 2 4]]
(map!
arr
&(fn [val] (* @val 2)))
arr)
"map! works as expected")
(assert-equal test
true
(empty? (the (Ref (StaticArray Int)) $[]))