Multidimensional List Solution

In a previous article, I wrote about how it was difficult to produce a 2D list in Copper due to the ownership dilemma. The solution at the time was to write a singly-linked list in Copper. It turns out, there is a better approach, one that will also allow us to create any multi-dimensional list.

Rather than making a list of lists, we take a somewhat Pythonic approach and make a list of functions each with a member that is a list. Recall that making a list of functions that directly hold lists resulted in our inability to alter them with item_at(). But if the sub-lists are stored in members of the functions in the main list, then we can directly access them. Rather than trying to explain the details, it’s easy enough just to show the code:

list2d = [
	items = list:
	add_row = {
		append(super.items: [items=list:])
	}
	item_at = [row column]{
		m~item_at(super.items: row:)
		e~item_at(m.items: column:)
		ret(e.item)
	}
	set_item = [row column item]{
		if ( gte(r: length(super.items:)) ) {
			loop {
				if ( gt(length(super.items:) row:) ) { stop }
				append(super.items: [items=list:])
			}
		}
		m~item_at(super.items: row:)
		if ( gte(column: length(m.items:)) ) {
			loop {
				if ( gt(length(m.items:) column:) ) { stop }
				append(m.items: [item={}])
			}
		}
		e~item_at(m.items: column:)
		e.item = item
	}
]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s