More on arrays
Now we are going to see a few more advanced words in the a (array) namespace.Iterating over an array – the word a:each
Later we will see that 8th has special words for iterating / looping.However, there are also words like a:each that make it very easy to use iteration under the hood, without having to bother with the details.
The SED of a:each is \ a w – a
- a = input array
- w = the helper word
The SED of show (in our example below) is \ index value --
- index = index of current array item
- value = value of current array item
So a:each is such a word, that takes another word as a parameter (as we saw in the previous lesson).
The show word will be handed the value of the item at TOS and it’s index in 2nd position on the stack.
Example
Note that we have to use swap in order to show the index before the value!
Note that 8th arrays can contain values of different types (unlike e.g. in C).
Output:
Note that a:each leaves the array on the stack after executing!
Reducing an array using a:reduce
Reducing is a process like this:- use an array
- get a start value x (which will be used as an accumulator)
- for every item in the array:
- do something with the values of the current array element and x (and also consume them)
- push the result on the stack; that value will then be used as the x value in the next iteration
The SED of a:reduce is \ a w x – x
- a = input array
- w = the helper word
- x = initial value, also used as an accumulator
The SED of sum (just an example word below) is \ value x -- newx
- value = value of current array item
- x = initial value, also used as the accumulator
Example
Output:
Filtering an array using a:filter
This word uses a helper word that returns either true or false.Only if that helper word retruns true, the corresponding element will be put in an output array.
The SED of a:filter is \ a1 w – a2
- a1 = input array
- w = the helper word
- a2 = output array
The SED of iseven (just an example word below) is \ value -- boolean
• value = value of current array item
• boolean = true or false
Example
Note that the not word regards the value 0 (zero) as false! So when value 0 is encountered, not will output true and otherwise false.
Output:
More info about 8th
8th Website: http://8th-dev.com8th Forum: http://8th-dev.com/forum
My YouTube Channel: https://goo.gl/DscYVD
My BLOG: http://goo.gl/n1NocJ






No comments:
Post a Comment