Tuples
A tuple is a finite ordered list of elements. In other words, it is an array.
Word | Action |
---|---|
EMPTY-TUPLE ( N -- tuple ) |
Creates and initialize a tuple of length N with each elements being NULL. |
TUPLE ( x1 x2 ... xN N -- tuple ) |
Creates and initialize a tuple of length N with the elements being x1, x2, ..., xN. |
TUPLE-LEN ( tuple -- n ) |
Returns the length of the tuple. |
@@ ( tuple k -- v ) |
Reads the value of the tuple at index k. The tuple will no longer be in the stack. |
!! ( tuple v k -- ) |
Writes the value of the tuple at index k to v. |
.TUPLE ( tuple -- ) |
Writes the contents of the tuple to screen. |
COPY ( tuple -- tuple' ) |
Puts a deep copy of a tuple to the stack. |
ARRAY>SEQ ( tuple -- seq ) |
Converts a tuple into a sequence. |
Examples
Example 15 empty-tuple .tuple (null,null,null,null,null)okExample 2
"hello" "world" 2 tuple .tuple (hello,world)okExample 3
"hello" "world" 2 tuple dup .s <2> [Ljava.lang.Object;@4ff278a5 [Ljava.lang.Object;@4ff278a5 ok copy .s <2> [Ljava.lang.Object;@4ff278a5 [Ljava.lang.Object;@391d11dc ok
-
Notice that for
DUP, both tuples are the same. This shows that both are the same tuple. But for
COPY, the second tuple is already different. In this case, these two are different tuples with the same content.
2 4 6 8 4 tuple dup .tuple (2,4,6,8)ok dup 0 @@ . 2 ok dup -10 3 !! .tuple (2,4,6,-10)ok
-
Note that we need to
DUPbefore rewriting the content of the tuple. If not, there will be nothing remained in the stack after rewriting. This is because
!!will take the tuple as an argument and not return any new tuple. The first tuple has also been modified because as mentioned in the previous example, both tuples are the same. So, the changes will be reflected on the other tuple.
Quiz
Question 1
Write a word..that takes two numbers (start & end) and produces a tuple which shows numbers from start to end, with skip of 1. You may need to use a loop.
: .. ( n1 n2 -- tuple ) { n1 n2 } n2 1 + n1 DO i LOOP n2 1 + n1 - tuple ; 2 2 .. .tuple cr \ (2) 0 10 .. .tuple cr \ (0,1,...,10) -1 3 .. .tuple cr \ (-1,0,1,2,3)
Question 2
Write a wordNESTED-TUPLESthat takes two numbers (m & n) and creates a tuple of size m with elements being tuples of size n. You may need to use a loop.
: NESTED-TUPLES ( m n -- tuple ) { m n } m 0 DO n empty-tuple LOOP m tuple ; 3 2 nested-tuples dup tuple-len . cr \ 3 dup .tuple cr dup 0 @@ dup . .tuple cr \ inner tuple 0, (null,null) dup 1 @@ dup . .tuple cr \ inner tuple 1, (null,null) dup 2 @@ dup . .tuple cr \ inner tuple 2, (null,null)