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 1
	5 empty-tuple .tuple
	(null,null,null,null,null)ok
	
Example 2
	"hello" "world" 2 tuple .tuple
	(hello,world)ok
	
Example 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.
Example 4
	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
    DUP
    before 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.



Question 2

 Write a word 
NESTED-TUPLES
that 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.



Next: XTs