1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393
|
/** -*-C-*-ish
Kaya standard library
Copyright (C) 2004, 2005 Edwin Brady
This file is distributed under the terms of the GNU Lesser General
Public Licence. See COPYING for licence.
*/
module Array;
import Builtins;
import Tuples;
foreign "stdfuns.o" {
[a] doReverse([a] xs) = reverseArray;
"Resize an array.
Change the size of the array to <em>i</em>. If the array is longer
than <em>i</em>, later items are dropper. If shorter, uninitialised
values are pushed onto the array."
public Void resize([a] xs, Int i) = resizeArray;
Void quicksort(Ptr vm, [a] xs, Int(a,a) sortfn) = quicksort;
Void shortenArray([a] array) = shortenArray;
a shiftArray([a] array) = shiftArray;
"Create an array with an initial size of <em>size</em>."
public [a] createArray(Int size) = createArray;
}
public Exception OutOfBounds = Exception("Out of bounds error",20);
"Reverse an array in-place."
public Void reverse(var [a] xs)
{
xs = doReverse(xs);
}
"Return an array of values from [first..last], incrementing by step."
public [Int] range(Int first, Int last, Int step = 1)
{
// print "Running range\n";
size = (last+1-first)/step;
if (size<0) { size=-size; }
xs = createArray(size);
j=0;
val = first;
if (step>0) {
while (val<=last) {
xs[j]=val;
j=j+1;
val = val + step;
}
} else if (step<0) {
while (val>=last) {
xs[j]=val;
j=j+1;
val = val + step;
}
}
return xs;
}
"Sort an array.
Uses quicksort algorithm.
By default uses built in compare function and sorts in
ascending order, but can also use a user supplied compare function."
public Void sort(var [a] xs, Int(a,a) sortfn = compare)
{
quicksort(getVM(),xs,sortfn);
// quicksort(xs, 0, size(xs)-1, sortfn);
}
"Return a sorted array.
Sorts an array, but unlike <em>sort</em> returns a new array and leaves
the original intact."
public [a] sorted([a] xs)
{
newxs = createArray(size(xs));
// Do a shallow copy.
for x in xs {
push(newxs,x);
}
sort(newxs);
return newxs;
}
"Randomly reorder an array."
public Void shuffle(var [a] xs)
{
// Swap each element with a random other element
xsize = size(xs);
for i in [0..xsize-1] {
swap(xs[i],xs[abs(rand()%xsize)]);
}
}
/*
Void quicksort([a] xs, Int left, Int right, Int(a,a) sortfn)
{
if (right>left) {
// Get the pivot from about the middle.
pi = partition(xs, left, right, (left+right)/2, sortfn);
quicksort(xs, left, pi-1, sortfn);
quicksort(xs, pi+1, right, sortfn);
}
}
Int partition(var [a] xs, var Int left, var Int right, var Int pivotIndex, var Int(a,a) sortfn)
{
pivotval = xs[pivotIndex];
swap(xs[pivotIndex], xs[right]); // Put pivot on the end
si = left;
for(i=left;i<right;i++) { // More efficient than "for x in xs"
if (sortfn(xs[i],pivotval)<0) {
swap(xs[si],xs[i]);
si++;
}
}
swap(xs[right],xs[si]); // Put pivot where it should be.
return si;
}
*/
"Concatenate two arrays."
public Void concat(var [a] xs, [a] ys)
{
for y in ys {
push(xs,y);
}
}
"DEPRECATED synonym for concat"
public Void append(var [a] xs, var [a] ys) = concat(xs,ys);
"Concatentate a list of lists into a single list."
public [a] join ([[a]] lists)
{
new = [];
for xs in lists {
for x in xs {
push(new,x);
}
}
return new;
}
"Place the separator <em>sep</em> between each element of <em>xs</em>."
public [a] intersperse(a sep, [a] xs)
{
new = createArray(size(xs)*2);
for x@i in xs {
push(new,x);
if (i!=size(xs))
push(new,sep);
}
return new;
}
"Return whether any of <em>xs</em> satsify predicate <em>p</em>."
public Bool any(Bool(a) pred, var [a] xs)
{
for x in xs {
if (pred(x)) {
return true;
}
}
return false;
}
"Return whether all of <em>xs</em> satsify predicate <em>p</em>."
public Bool all(Bool(a) pred, [a] xs)
{
for x in xs {
if (!pred(x)) {
return false;
}
}
return true;
}
"Map a function across an array.
Returns the array created by applying function <em>f</em> to every
element of <em>xs</em>."
public [b] map (b(a) f, [a] xs) {
newxs = createArray(size(xs));
for x in xs {
push(newxs, f(x));
}
return newxs;
}
// If we have map, we might as well have zipWith!
"Map a function across two arrays.
Returns the array created by applying function <em>f</em> to every pairwise
elements of <em>xs</em> and <em>ys</em>."
public [c] zipWith(c(a,b) f, [a] xs, [b] ys) {
if (size(xs)<size(ys)) {
max = size(xs);
} else {
max = size(ys);
}
newxs = createArray(max);
for i in [0..max-1] {
push(newxs, f(xs[i],ys[i]));
}
return newxs;
}
"Turn a pair of lists into a list of pairs."
public [(a,b)] zip([a] xs, [b] ys) {
return zipWith(lambda(a,b) -> { (a,b) }, xs, ys);
}
"Fold an array.
Applies a function across an array. Example, given a function <code>sum</code>
which adds two numbers:
<pre>
total = fold(sum,[1,2,3,4,5],0);
putStrLn(String(total));
</pre>
This prints the sum of the values in the array <code>[1,2,3,4,5]</code>."
public b fold (b(a,b) f, [a] xs, b acc) {
for x in xs {
acc = f(x,acc);
}
return acc;
}
"Filter a list according to a predicate.
Each element of <em>xs</em> is tested against the predicate <em>p</em>.
The returned list contains those elements of <em>xs</em> for which the
predicate is true."
public [a] filter(Bool(a) p, [a] xs) {
newxs = createArray(size(xs));
for x in xs {
if (p(x)) push(newxs,x);
}
return newxs;
}
"Push a value onto the end of an array."
public Void push(var [a] array,var a v)
{
array[size(array)]=v;
}
public a top([a] array)
{
if (size(array)==0) {
throw(OutOfBounds);
}
return array[size(array)-1];
}
"Remove a value from the end of an array"
public Void pop(var [a] array) {
if (size(array)==0) {
throw(OutOfBounds);
}
shortenArray(array);
}
"Get the first item off an array, and remove it from the array."
public a shift(var [a] array)
{
if (size(array)==0) {
throw(OutOfBounds);
}
return shiftArray(array);
/* x = array[0];
for(i=0;i<(size(array)-1);i=i+1) {
array[i]=array[i+1];
}
shortenArray(array);
return x;*/
}
"Opposite of shift; put a value on the front of an array."
public Void unshift(a val, var [a] array)
{
for(i=size(array)-1;i>=0;i=i-1) {
array[i+1]=array[i];
}
array[0]=val;
}
"Return the subarray starting at position pos, n elements long."
public [a] subarray([a] array, Int pos, Int n)
{
if (pos < 0 || n < 1 || pos+n > size(array)) {
throw(OutOfBounds);
}
sub = createArray(n);
for i in [pos..(pos+n-1)] {
push(sub,array[i]);
}
return sub;
}
"Return the array created by removing a subarray.
Subarray starts at position pos, n elements long."
public [a] remove([a] array, Int pos, Int n)
{
// subarray() does the bounds checking for us here.
sub = subarray(array,pos,n);
for i in [pos..(size(array)-n-1)] {
array[i] = array[i+n];
}
for i in [1..n] {
pop(array);
}
return sub;
}
"Remove the element at position <em>idx</em>."
public Void removeAt(var [a] array, Int idx)
{
if (size(array)<=idx) {
throw(OutOfBounds);
}
for(i=idx;i<(size(array)-1);i=i+1) {
array[i]=array[i+1];
}
shortenArray(array);
}
"DEPRECATED synonym for removeAt()"
public Void removeidx(var [a] array, Int idx) = removeAt(array,idx);
"Add an element at position <em>idx</em>"
// idx = 0 is equivalent to unshift, idx = size(array) is equivalent to push
public Void addAt(var [a] array, a elem, Int idx)
{
if (size(array)<idx) {
throw(OutOfBounds);
} else if (size(array) == idx) {
push(array,elem);
} else {
for(i=size(array);i>=idx;i--) {
array[i]=array[i-1];
}
array[idx] = elem;
}
}
"DEPRECATED synonym for addAt()"
public Void addidx(var [a] array, a elem, Int idx) = addAt(array,elem,idx);
"Return whether val is in list."
public Bool elem(a val, [a] list, Bool(a,a) eq = equal) {
// this should probably be optimised at compile time
// rather than with less neat code here, but it is a
// commonly-used function
for x in [0..size(list)-1] {
if (eq(list[x],val)) {
return true;
}
}
return false;
}
"Remove repeated elements from a list (in-place modification).
The name 'nub', incidentally, is borrowed from the Haskell prelude function
of the same name, and suggests 'essence'."
public Void nub(var [a] xs, Bool(a,a) eq = equal) {
pos = 1;
while (pos < size(xs)) {
if (elem(xs[pos],take(pos,xs),@eq)) {
removeAt(xs,pos);
} else {
pos++;
}
}
}
"Take the first <em>n</em> elements from an array.
Returns a new array, leaving the original unmodified."
public [a] take(Int x, [a] xs) = subarray(xs,0,x);
/*{ // might as well only implement subarray once
if (size(xs)<x) {
x = size(xs);
}
retxs = [];
for i in [0..x-1] {
push(retxs,xs[i]);
}
return retxs;
}*/
|