Arrays: Difference between revisions

528 bytes added ,  8 years ago
m
→‎{{header|Babel}}: Updated to interactive-mode syntax
m (→‎{{header|Babel}}: Updated to interactive-mode syntax)
Line 563:
===Create an array===
 
There are two kinds of array in Babel: value-arrays and pointer-arrays. A value-array is a flat array of data words. A pointer-array is an array of pointers to other things (including value-arrays). You can create a data-array with plain square-brackets. You can create a value-array with the [ptr ] list form:
<lang babel>[val 1 2 3]</lang>
 
<lang babel>[val 1 2 3]</lang>
OR
 
<lang babel>[ptr 1 2 3]</lang>
 
There are two kinds of array in Babel: value arrays and pointer arrays.
 
===Get a single array element===
 
<lang babel>[val 1 2 3] 1 th ;</lang>
 
{{Out}}
Yields 2
<pre>[val 0x2 ]</pre>
 
===Change an array element===
 
<lang babel>[val 1 2 3] 7dup 1 paste</lang>7 set ;
</lang>
 
{{Out}}
Yields [val 1 7 3]
<pre>[val 0x1 0x7 0x3 ]</pre>
 
<lang babel>[ptr 1 2 3] dup 1 [ptr 7] 1set paste;</lang>
 
{{Out}}
Yields [ptr 1 7 3]
<pre>[ptr [val 0x1 ] [val 0x7 ] [val 0x3 ] ]</pre>
 
===Select a range of an array===
 
<lang babel>[ptr 'foo'1 'bar'2 'baz'3 'bop'4 5 6] 1 3 slice ;</lang>
 
{{Out}}
Yields [ptr 'bar' 'baz']
<pre>[ptr [val 0x2 ] [val 0x3 ] ]</pre>
 
===Add a new element to an array===
 
You can concatenate arrays of same type:
There is no direct method to add a new element to an array in Babel. Instead, you should convert the array to a list using the ar2ls operator, then add to the list. When you are finished manipulating the list, convert back to an array using either the bons operator or the ar2lf operator.
 
<lang babel>[1 2 3] [4] cat</lang>
The other method is to create a new larger array and copy the old array into it, then add the additional element. However, this method is "un-Babelish":
 
<lang babel>[ptr 1 2 3] [ptr 4] cat</lang>
 
[ptr 1 2 3] dup
Concatenation creates a new array - it does not add to an array in-place. Instead, Babel provides operators and standard utilities for converting an array to a list in order to manipulate it, and then convert back.
<- arlen 1 + newin dup dup ->
 
0 paste
===Converting between arrays and lists===
[ptr 4] 3 paste
 
</lang>
<lang babel>[1 2 3] ar2ls lsnum !</lang>
 
{{Out}}
<pre>( 1 2 3 )</pre>
 
<lang babel>(1 2 3) ls2lf ;</lang>
 
{{Out}}
<pre>[val 0x1 0x2 0x3 ]</pre>
 
<lang babel>[ptr 'foo' 'bar' 'baz'] ar2ls lsstr !</lang>
 
{{Out}}
<pre>( "foo" "bar" "baz" )</pre>
 
<lang babel>(1 2 3) bons ;</lang>
Yields [ptr 1 2 3 4].
 
{{Out}}
The Babelish method:
<pre>[ptr [val 0x1 ] [val 0x2 ] [val 0x3 ] ]</pre>
 
To learn more about manipulating arrays and lists in Babel, type "help !" (no quotes) and follow the instructions to load the man.sp file.
<lang babel>
[ptr 1 2 3]
ar2ls (4) unshift bons</lang>
 
=={{header|BASIC}}==
Anonymous user