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 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611
|
/** -*-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.
*/
"<summary>Built-in functions</summary>
<prose>This module contains built-in functions that are used by the Kaya
run-time, functions required by the rest of the Prelude, and other
fundamental functions.</prose>
<prose>It is automatically imported (via the Prelude module) unless
the <code>-noprelude</code> compiler option is used. All programs must
import this module, and most modules will need to.</prose>"
module Builtins;
/* The only global we use in this module is to seed the random number
generator.
*/
globals {
Int randseed;
}
// Exception thrown by foreign code
"<argument>An internal code for the Exception is contained in the Int</argument>
<summary>Thrown by the run-time system and foreign functions.</summary>
<prose>This Exception may be thrown by run-time system calls or foreign functions.</prose>"
Exception InternalError(Int code);
// Now for some built in exceptions in the run-time system
// (CONVENTION NOTE, ECB 1/3/07: I put underscores in these because they are
// meant to be read as error messages rather than caught by user programs. If
// this is considered ugly or offends anyone's sense of style, sorry :).
// I don't think it's important enough to worry about though...)
"<summary>Tried to read a field incorrectly</summary>
<prose>This Exception is thrown when a field is projected from a data type that does not have fields, for example:</prose>
<example>a = \"Hello\".world;</example>
<prose>In the example, the compiler would catch the error - in practice this error can occur when accessing an uninitialised value, or a value with inconsistent type information due to foreign function calls.</prose>"
Exception Project_From_Non_Union();
"<summary>Tried to lookup in an array</summary>
<prose>This Exception is thrown when an array lookup is performed on something other than an array:</prose>
<example>a = \"Hello\"[1];</example>
<prose>In the example, the compiler would catch the error - in practice this error can occur when accessing an uninitialised value, or a value with inconsistent type information due to foreign function calls.</prose>"
Exception Lookup_From_Non_Array();
"<summary>Array index must be non-negative</summary>
<prose>Array indexes vary from 0 to (2**31)-1. Negative array indexes are not allowed and will return this Exception.</prose>"
Exception Negative_Array_Index();
"<summary>Tried to get a field from the wrong constructor</summary>
<prose>This exception is thrown when direct projection of a field is used on a value constructed with a different constructor. It can always be avoided by the use of <code>case</code> statements.</prose>
<example>data Example = A(Int a) | B(String b);
Void main() {
val = A(3);
putStrLn(val.b);
}</example>"
Exception Wrong_Constructor();
"<summary>Tried to do a constructor <code>case</code> statement wrongly</summary>
<prose>This Exception is thrown when a <code>case</code> statement is used on something other than an ADT, for example:</prose>
<example>i = 5;
case i of {
A(a) -> putStrLn(a);
| B(b) -> putStrLn(b);
}</example>
<prose>In the example, the compiler would catch the error - in practice this error can occur when accessing an uninitialised value, or a value with inconsistent type information due to foreign function calls.</prose>"
Exception Getting_Tag_From_Non_Union();
/* // call stack now expands properly
"<summary>Too many recursive function calls</summary>
<prose>If there are too many function calls inside each other, the call stack will overflow and cause this Exception. Call stack overflow can often be avoided using \"tail recursion\" and adding an accumulating parameter.</prose>
<example>Int triangle(Int a) {
if (a <= 1) {
r = 1;
} else {
r = a+triangle(a+1);
}
return r;
}
Int triangleTR(Int a, Int acc = 1) {
if (a <= 1) {
return acc;
} else {
return triangleTR(a+1, a+acc);
}
}</example>
<prose>The <code>triangleTR</code> function calls itself as its last action before returning, and so a tail recursion optimisation can be made to avoid inflating the call stack.</prose>"
Exception Call_Stack_Overflow(); */
"<summary>The unmarshal ID was invalid</summary>
<prose>The <functionref>unmarshal</functionref> was passed a marshalling ID that was not the same as the one used to <functionref>marshal</functionref> the data.</prose>
<related><functionref>marshal</functionref></related>
<related><functionref>unmarshal</functionref></related>"
Exception Invalid_Marshalling_ID();
"<summary>The function table has changed</summary>
<prose>The <functionref>unmarshal</functionref> was passed a marshalled String where the program function table is different to the one used to <functionref>marshal</functionref> the data. Marshalling and unmarshalling may only be done reliably within one instance of a program binary (though may be done across multiple invocations).</prose>
<related><functionref>marshal</functionref></related>
<related><functionref>unmarshal</functionref></related>"
Exception Invalid_Function_Table_Hash();
"<summary>Invalid or uninitialised value</summary>
<prose>This Exception is usually thrown when operations are carried out on an uninitialised value, for example:</prose>
<example>xs = [];
xs[0] = \"Hello\";
if (xs[0] == xs[300]) {
// Invalid_Value thrown
}</example>
<prose>It may also be thrown by <functionref>unmarshal</functionref> if the marshalled String is corrupt.</prose>"
Exception Invalid_Value();
"<summary>Not implemented yet</summary>
<prose>This exception is thrown if a function is called that is not implemented yet, or is not applicable in the current situation.</prose>"
Exception Not_Implemented();
"<summary>Marshal string describes an impossible structure</summary>
<prose>This Exception is thrown by <functionref>unmarshal</functionref> where the marshalled String describes an impossible circular structure.</prose>"
Exception Invalid_Circular_Structure();
"<summary>Exceptions may not be marshalled</summary>
<prose>This Exception will be thrown if you attempt to <functionref>marshal</functionref> an Exception.</prose>"
Exception Cant_Marshal_Exceptions();
"<summary>Exceptions may not be reflected</summary>
<prose>This Exception will be thrown if you attempt to <moduleref>Reflect</moduleref> an Exception.</prose>"
Exception Cant_Reflect_Exceptions();
/*"<summary>DEPRECATED</summary>
<prose>This Exception is only thrown by a run-time system function that should never be called.</prose>" // stdfuns.cc::callFnID doesn't appear to be used anywhere
Exception Unknown_Function_ID(); */
"<summary>Unexpected constructor in <code>case</code> statement</summary>
<prose>This Exception is thrown when a constructor with no explicitly defined behaviour was used in a <code>case</code> statement, and there was no <code>default</code> case.</prose>
<example>data Example = A(Int a) | B(String b) | C(Float c);
Void string(Example e) {
case e of {
A(a) -> return String(a);
| B(b) -> return b;
}
} // if e = C(1.0) then a Missing_Case exception will be thrown.</example>"
Exception Missing_Case();
"<summary>Pattern matching assignment failed</summary>
<prose>This Exception is thrown in a pattern matching assignment if the
right hand side of the assignment does not match the pattern given on the
left hand side.</prose>
<example>testlist = nil;
let cons(x,xs) = testlist; // testlist is nil, not cons
</example>
"
Exception Pattern_Matching_Assignment_Failure();
"<summary>Unexpected case in shorthand</summary>
<prose>This Exception is thrown when a shorthand syntax is used and an unexpected case occurs.</prose>
<example>Int mag(Int x) | x<0 = -x;
| x>0 = x;
//Calling this function with x==0 throws this exception</example>"
Exception Unguarded_Guard();
"<summary>Tried to divide by zero.</summary>
<prose>This Exception is thrown when an attempt to divide by zero is made.</prose>" // RTS defined.
Exception Divide_By_Zero();
// Inserted to calls to traverse. Not sure I want to document these since
// they are an implementation detail. Is there a way we can hide them from
// the output?
Exception Loop_Return(a val);
Exception Loop_VoidReturn();
foreign "stdfuns.o" {
"<argument name='xs'>An array</argument>
<summary>Length of an array</summary>
<prose>Return the length of an array.
The empty array has length 0, and uninitialised elements are considered
to exist for the purposes of determining length.</prose>
<example>arr = [];
arr[5] = 26;
l = length(arr); // 6</example>"
pure public Int size([a] xs) = arraySize;
"<argument name='s'>The string to check</argument>
<summary>Check whether a string contains UTF8 characters</summary>
<prose>Scans a string looking for non-ASCII characters; returns True
if any are present.</prose>"
pure public Bool UTF8(String s) = checkUTF8;
pure Int doByteLength(String s, Int i) = binary_length;
"<argument name='val'>Any variable</argument>
<summary>Debugging function</summary>
<prose>Debugging function for Kaya development: Returns the number of heap bytes used to store <variable>val</variable>.</prose>"
public Int memUsage(a val) = funtable_memusage;
pure Int doHash(a x) = funtable_hash;
pure String doMarshal(Ptr vm, a x, Int id) = funtable_marshal;
pure any doUnmarshal(Ptr vm, String x, Int id) = unmarshal;
pure Int doCompare(Ptr vm, a x, a y) = funtable_compare;
pure Bool doEqual(Ptr vm, a x, a y) = funtable_eq;
pure Char doGetIndex(String s, Int i) = getIndex;
Void doSetIndex(String s, Char c, Int i) = setIndex;
any doCopy(Ptr vm, any x) = funtable_copy;
pure a unsafe_id(b x) = unsafe_id;
"<argument name='x'>A possibly initialised variable</argument>
<summary>Checks if a value is initialised</summary>
<prose>Returns true if the value is initialised, or false if not
(for example, an uninitialised array element)</prose>
<example>arr = [];
arr[2] = 55;
b = isInitialised(arr); // true
b = isInitialised(arr[2]); // true
b = isInitialised(arr[1]); // false</example>"
public Bool isInitialised(a x) = is_initialised;
"<argument name='x'>The item to get the address of</argument>
<summary>Debugging function</summary>
<prose>Debugging function for developer use.</prose>"
public pure String getAddr(a x) = getAddr;
pure Bool isNull(Ptr p) = isNull;
pure Bool isIdentical(a x, a y) = isIdentical;
pure Int doGetFnID(fn f) = doGetFnID;
"<prose>Return hash of function table.</prose>
<summary>Internal function.</summary>"
public Int funtableHash() = getFnHash;
pure Int except_code(exc e) = except_code;
pure String except_msg(exc e) = except_msg;
Void except_dump(exc e) = except_dumpbt;
Int doStrAlloc(str e) = strAlloc;
str doCreateString(Ptr vm,Int len) = createString;
Int doStrHash(String s, Int i) = strHash;
"<summary>Is run-time checking enabled?</summary>
<prose>Return whether the executable was compiled with run-time checking.
True, unless -nortchecks was used for the main program. Should be used
with some care, since if abused this can mean the program exhibits
very different behaviour depending on whether checking is on or off.</prose>"
public Bool runTimeChecking() = rtchecks;
"<argument name='code'>The exit code</argument>
<summary>End the application immediately</summary><prose>End the application and exit immediately with the given exit code. An exit code of zero is traditionally used for successful completion.</prose>
<prose>It is generally a bad idea to use this function in web applications.</prose>
<related><functionref>System::_exit</functionref></related>"
public Void exit(Int code) = exit;
}
"<argument name='s'>The String to hash</argument><summary>Get a numeric hash of a string.</summary><prose>Returns a numeric hash of a String. This is most useful for hashing efficiency when working with <moduleref>Dict</moduleref>s with String keys, and similar.</prose>"
public Int strHash(String s) = doStrHash(s,length(s));
"<argument name='s'>The string to measure</argument>
<summary>Length of a String</summary>
<prose>Get the length of a String. This gives the length in Chars.</prose>
<prose>Compare with <functionref>Builtins::byteLength</functionref>.</prose>"
public Int length(String s) = %length(s);
"<argument name='s'>The string to measure</argument>
<summary>Length in bytes of a string</summary>
<prose>Get the length in bytes of a String (allowing for multi-byte characters in a UTF-8 encoding).</prose>
<example>str = \"Hello multibyte: \"+Char(192);
l = length(str); // 18
ml = byteLength(str); // 19</example>
<related><functionref>length</functionref></related>"
public Int byteLength(String s) = doByteLength(s,length(s));
"<summary>Index is out-of-bounds or otherwise illegal</summary>
<prose>This Exception is thrown when an index is out-of-bounds. It is used by <functionref>getIndex</functionref> if the index is negative or higher than the length of the string.</prose>"
Exception IllegalIndex();
"<summary>Strings may not contain null bytes</summary>
<prose>This Exception is thrown if you try to set a character in a String to a null byte with <functionref>setIndex</functionref></prose>"
Exception NoNullsInStrings;
"<argument name='s'>The string</argument>
<argument name='i'>The position in the string</argument>
<summary>Get a character from a String</summary>
<prose>Get a character from a String.
Gets the <variable>i</variable>th character of the given String. The index starts at zero.</prose>
<example>str = \"abcdefg\";
c = getIndex(str,0); // 'a'
c = getIndex(str,5); // 'f'</example>
<prose>An <exceptref>IllegalIndex</exceptref> exception is thrown if <variable>i</variable> is out of bounds.</prose>
<related><functionref>setIndex</functionref></related>"
public Char getIndex(String s, Int i) {
if (i<0 || i >= length(s)) {
throw(IllegalIndex);
}
return doGetIndex(s,i);
}
"<argument name='s'>The string</argument>
<argument name='c'>The character to set (may not be a NULL)</argument>
<argument name='i'>The position in the string</argument>
<summary>Change a character in a String in-place</summary>
<prose>Sets the <variable>i</variable>th character of the given String to the given character. The index starts at zero.</prose>
<example>str = \"abcdefg\";
setIndex(str,'-',4); // str = \"abcd-fg\"</example>
<prose>An <exceptref>IllegalIndex</exceptref> exception is thrown if <variable>i</variable> is out of bounds.</prose>
<related><functionref>getIndex</functionref></related>"
public Void setIndex(String s, Char c, Int i) {
if (i<0 || i >= length(s)) {
throw(IllegalIndex);
} else if (Int(c) == 0) {
throw(NoNullsInStrings);
}
doSetIndex(s,c,i);
}
"<argument name='s'>The string to translate</argument>
<argument name='rule'>The rule to apply</argument>
<summary>Translate characters in a String</summary>
<prose>Replace characters in a String in place, applying the translation function to each character in turn.</prose>
<example>Char rot13(Char c) {
if ((c >= 'A' && c <= 'M') ||
(c >= 'a' && c <= 'm')) {
return Char(c+13);
} else if ((c >= 'N' && c <= 'Z') ||
(c >= 'n' && c <= 'z')) {
return Char(c-13);
} else {
return c;
}
}
Void main() {
str = \"Hello World\";
translate(str, rot13);
// str = \"Uryyb Jbeyq\";
}</example>"
public Void translate(var String s, Char(Char) rule) {
l = length(s);
// can't use [..] range as it's not defined yet!
// so use a while() loop instead
i = 0;
while (i<l) {
// already done bounds-check, so call doSet/Get directly
doSetIndex(s,rule(doGetIndex(s,i)),i);
i++;
}
}
"<argument name='x'>The value to marshal</argument>
<argument name='id'>The unmarshalling ID</argument>
<summary>Marshal any value to a string</summary>
<prose>Return a machine readable <code>String</code> representation of a variable of any type.</prose>
<prose>The <variable>id</variable> given must be identical when unmarshalling to provide some protection against accidentally unmarshalling the wrong value.</prose>
<prose>Marshalling is intended for passing complex data between two separate
instances of the same program. The format is not guaranteed to be the same
between versions of the standard library. Also note that if you are
marshalling closures, the representation may change when you recompile
(as the marshalled form of a closure is based on its function id, generated at compile time). Therefore, Kaya will not unmarshal a representation generated by a program with a different function table.</prose>
<prose>To pass data other than closures between two programs, in a way that will continue to work in different library versions, consider the <moduleref>Pickle</moduleref> module.</prose>
<prose>Note that <code>a==b</code> does not necessarily imply <code>marshal(a,i)==marshal(b,i)</code> as the marshalling format includes some internal representation details for the virtual machine that do not affect equality. This is unlikely to be a problem in most cases (and <code>unmarshal(marshal(a,i),i)==unmarshal(marshal(b,i),i)</code> is always true if <code>a==b</code>!).</prose>
<related><functionref>Pickle::pickle</functionref></related>
<related><functionref>unmarshal</functionref></related>"
public String marshal(any x,Int id) {
return doMarshal(getVM(),x,id);
}
"<argument name='x'>The String to unmarshal</argument>
<argument name='id'>The unmarshalling ID</argument>
<summary>Unmarshal a string</summary>
<prose>Convert a String generated with <functionref>marshal</functionref> into a variable of the appropriate type.</prose>
<prose>This must be done with care, since the type you get depends on the
String, so make sure you know what you are doing! The id given must
match the id given when marshalling or an Exception is generated.</prose>
<prose>An Exception will also be generated if the function table of the current program does not match the function table of the marshal()ing program.</prose>
<related><functionref>marshal</functionref></related>
<related><functionref>Pickle::unpickle</functionref></related>"
public any unmarshal(String x, Int id) {
return doUnmarshal(getVM(),x,id);
}
"<argument name='x'>The first value to compare</argument>
<argument name='y'>The second value to compare</argument>
<summary>Compare two values for \"size\"</summary>
<prose>Compare any two values of the same type.
Returns 0 if they are equal, less than zero if <variable>x</variable> is smaller, or greater than
zero if <variable>x</variable> is bigger.</prose>"
public Int compare(any x, any y)
{
return doCompare(getVM(),x,y);
}
"<summary>Equality check</summary>
<prose>Check any two values for equality. Returns <code>true</code> if they are equal, <code>false</code> otherwise. <code>equal(a,b)</code> is equivalent to <code>a == b</code>.</prose>
<related>Compare with <functionref>identical</functionref>.</related>"
public Bool equal(any x, any y)
{
return doEqual(getVM(),x,y);
}
"<argument name='x'>The value to hash</argument>
<summary>Hash a value</summary>
<prose>Return an integer hash of any value. Because <code>hash</code> uses <functionref>marshal</functionref>, the hash is not guaranteed to be the same except within the same program binary.</prose>
<related><functionref>strHash</functionref></related>"
public Int hash(any x)
{
return doHash(x);
}
"<argument name='x'>The value to copy</argument>
<summary>Copy a value</summary>
<prose>Create a deep copy of any value.
Contrasting with assignment, which creates another reference, this
function traverses the entire structure and creates a clone.
Note that this function is <emphasis>not</emphasis> pure, as even called with the same
input, it returns a <emphasis>different</emphasis> copy each time.</prose>
<example>a = [5,6,7];
myFunction(a); // pass by shallow copy
myFunction(copy(a)); // pass by deep copy</example>
<prose>Copying a structure containing a foreign pointer (for example a database or file handle, or a piece of binary data) will copy the pointer but will <emphasis>not</emphasis> copy the contents of that pointer.</prose>"
public any copy(any x)
{
return doCopy(getVM(),x);
}
"<argument name='x'>The variable to change the type of</argument>
<summary>Subvert the type system.</summary>
<prose>Somebody is bound to want to do an unsafe cast, so I guess I'll let them.
I wanted to call this \"EnoughRopeToHangYourselfWith\" but I think it might
turn out to be too useful in creating bindings to external libraries to
have a name like that...</prose>"
public anything subvert(something x)
{
return unsafe_id(x);
}
"<summary>Get a pointer to the Kaya VM</summary>
<prose>Return a pointer to the virtual machine state.</prose>
<prose>Used by some foreign functions which need access to the virtual machine
for such things as throwing exceptions.</prose>"
public Ptr getVM() {
return %VM;
}
"<argument name='e'>The caught <code>Exception</code></argument>
<summary>Get a human-readable error message</summary>
<prose>Return the error message in an Exception. This is useful for determining the exception caught by a catch-all clause, but it is preferable to catch Exceptions by name.</prose>
<example>try {
functionThatMayGoWrong(a,b,c);
} catch(e) {
putStrLn(\"Something went wrong: \"+exceptionMessage(e));
}</example>
<related><functionref>exceptionBacktrace</functionref></related>
<related><functionref>exceptionCode</functionref></related>"
public String exceptionMessage(Exception e) {
return except_msg(e);
}
"<argument name='e'>The caught <code>Exception</code></argument>
<summary>Print the backtrace of an Exception.</summary>
<prose>This is used to deal with uncaught exceptions in programs and prints the
backtrace on standard output. It is generally not appropriate for use within
a program except for debugging purposes, and should never be called within a CGI program or webapp.</prose>
<prose>If the program is compiled with the <code>-nortchecks</code> compiler option then the backtrace will be of limited use. Similarly, the standard library must be compiled with the <code>--enable-debug</code> configure option to get useful backtraces there.</prose>
<related><functionref>exceptionCode</functionref></related>
<related><functionref>exceptionMessage</functionref></related>"
public Void exceptionBacktrace(Exception e) {
except_dump(e);
}
"<summary>Debugging function</summary>
<prose>Return the amount of memory allocated for a string, for debugging purposes.</prose>"
public Int strAlloc(String x) {
return doStrAlloc(x);
}
"<summary>Internal standard library function</summary>
<prose>Return the function id of <var>fn</var>.</prose>
<prose>Used by CGI (not webapp) event handlers, to know which function to call
on entry to the web application, and by other parts of the standard library.
Generally this function should not be used outside standard library development.</prose>"
public Int fnid(Void(a) fn) {
return doGetFnID(fn);
}
"<argument name='p'>The foreign <code>Ptr</code> to check.</argument>
<summary>Checks if a foreign pointer is NULL</summary>
<prose>Returns true if the foreign pointer is NULL. This is useful in testing whether a foreign function returns something valid,
before throwing an exception. This is the only way, in general, that
<code>Ptr</code> should be queried in Kaya; usually it is better to manipulate
pointers C side.</prose>"
public Bool null(Ptr p) {
return isNull(p);
}
"<argument name='x'>First value</argument>
<argument name='y'>Second value</argument>
<summary>Return whether two values are identical.</summary>
<prose>Check if two values are identical. This is stronger than equality - this tests whether two values are stored at the
same memory location. In other words, it tests whether modifying the contents
of <variable>x</variable> would also modify the contents of <variable>y</variable>.</prose>
<example>a = (5,6);
b = (3,a.snd);
c = a;
d = (5,6);
test = identical(b,a); // false
test2 = identical(b.snd,a.snd); //true
test3 = identical(c,a); // true
test4 = identical(d,a); // false</example>
<prose>Of course, <code>equal(a,d)</code> would be <code>true</code>.</prose>
<related><functionref>equal</functionref></related>"
public Bool identical(a x, a y) {
return isIdentical(x,y);
}
// Some functions which are so primitive that the rest of the prelude needs
// them...
"<argument name='x'>First variable</argument>
<argument name='y'>Second variable</argument>
<summary>Swap the contents of two variables</summary>
<prose>Swap the contents of two variables of the same type.</prose>
<example>a = 5;
b = 6;
swap(a,b);
// a = 6, b = 5</example>"
public Void swap(var a x, var a y)
{
tmp = x;
x = y;
y = tmp;
}
// Removed temporarily since VM instructions are commented out.
// "Return maximum memory usage over the whole program"
// public Int maxHeapSize = do_max_heapsize(getVM);
// added by CIM 11/9/2005
"<argument name='seed'>The initial seed</argument>
<summary>Seeds the random number generator</summary>
<prose>Seeds the random number generator. This must be called before any calls to <functionref>rand</functionref> are made. Seeding with the same integer will give the same sequence of pseudo-random numbers. Where unpredictability is not crucial, the <functionref>Time::time</functionref> function can be used to give a different sequence each time the program is run.</prose>
<related><functionref>rand</functionref></related>"
public Void srand(Int seed) {
randseed = seed;
}
"<summary>Pseudo-random signed integer generator</summary>
<prose><code>rand()</code> returns a pseudo-random signed integer in the range +/- (2**31)-1</prose>
<prose>You must call <functionref>srand</functionref> before the first call to this function in a program.</prose>
<example>srand(12345);
for i in [1..5] {
putStr(rand()+\" \");
}</example>
<prose>Gives: <output>1995772607 -612336503 -885735441 457910745 1875493919 </output></prose>
<prose>The <code>rand()</code> function is a low-quality but fast generator - for better quality numbers, use the optional <moduleref>Lfrand</moduleref> module or for cryptographic purposes, your computer's hardware RNG.</prose>
<related>The <functionref>Builtins::srand</functionref> function</related>
<related>The <moduleref>Lfrand</moduleref> module</related>"
public Int rand() {
return dorand()|(dorand()<<16);
}
// the low bits of an LCG have appalling properties, so take two sets of
// high bits instead. It's still not brilliant, but at least things like
// rand()%2==0 now have a ~50% instead of 100% or 0% chance!
Int dorand() {
randseed = ((62089911*randseed));//%((2**31)-1));
return ((randseed>>16)&((1<<16)-1));
}
"<argument name='x'>The integer to find the magnitude of</argument>
<summary>Return the magnitude of an integer.</summary>
<prose>Return the magnitude of an integer.</prose>
<example>a = abs(5); // 5
a = abs(-3); // 3</example>"
public Int abs(Int x) | x<0 = (-x)
| default = x;
"<argument name='x'>The floating-point variable to find the magnitude of</argument>
<summary>Return the magnitude of a floating-point number.</summary>
<prose>Return the magnitude of a floating-point number.</prose>
<example>a = abs(5.7); // 5.7
a = abs(-11.2); // 11.2</example>"
public Float abs(Float x) | x<0 = (-x)
| default = x;
"<summary>Creates a string with particular memory allocation</summary>
<argument name='len'>The number of characters to allocate space for</argument>
<prose>Create an empty string, with initial space for <variable>len</variable> characters.
Use this to avoid unnecessary reallocation if you know or can compute
the length of a string in advance.</prose>
<prose>Using this function can save time and memory in Kaya programs, but generally the default memory allocation will be adequate - save this for the optimisation stage.</prose>
<related><functionref>Array::createArray</functionref></related>"
public String createString(Int len)
{
return doCreateString(getVM,len);
}
"<summary>Returns a new reference to the original value.</summary>
<prose>Returns a new reference to the original value - i.e. the 'identity transformation'.</prose>
<example>a = (1,2,3);
b = identity(a);
// identical(a,b) == true</example>
<prose>Sometimes useful where a function is needed as a parameter.</prose>"
public a identity(a val) {
return val;
}
"<summary>Boolean NOT</summary>
<prose>The boolean NOT operator in function form.</prose>
<example>a = true;
b = inverse(a); // false</example>"
public Bool inverse(Bool val) {
return !val;
}
|