Mercurial > repos > other > SevenLanguagesInSevenWeeks
comparison 2-Io/day2-self-study.io @ 40:82627dd71c75
Implement 2D list/array
author | IBBoard <dev@ibboard.co.uk> |
---|---|
date | Thu, 14 Sep 2017 20:24:25 +0100 |
parents | c48e6e454991 |
children | f4ea1f637f22 |
comparison
equal
deleted
inserted
replaced
39:c48e6e454991 | 40:82627dd71c75 |
---|---|
87 # With default behaviour then this could divide by zero (unless we'd been defensive coding) | 87 # With default behaviour then this could divide by zero (unless we'd been defensive coding) |
88 # But we're in the same file as our custom "/", so we should get zero | 88 # But we're in the same file as our custom "/", so we should get zero |
89 list() myAverage println | 89 list() myAverage println |
90 | 90 |
91 | 91 |
92 #5) 2D list | |
93 TwoDList := Object clone | |
94 # It'd be nice to do something to set defaults when first cloning | |
95 # but I can't find how to do that, so force the developer to | |
96 # always dim() after clone | |
97 TwoDList dim := method(x, y, | |
98 self arr := list() | |
99 for (i, 1, x, | |
100 sub_list := list() | |
101 for (j, 1, y, | |
102 sub_list append(nil) | |
103 ) | |
104 arr append(sub_list) | |
105 ) | |
106 ) | |
107 TwoDList set := method(x, y, value, | |
108 self arr at(x) atPut(y, value) | |
109 ) | |
110 | |
111 TwoDList get := method(x, y, | |
112 outer := self arr at(x) | |
113 if (outer != nil, | |
114 return outer at(y), | |
115 return nil | |
116 ) | |
117 ) | |
118 | |
119 my_arr := TwoDList clone | |
120 my_arr dim(2, 3) | |
121 my_arr println | |
122 my_arr set(0, 1, "0,1") | |
123 my_arr set(1, 2, "Bottom-right") | |
124 my_arr get(1, 2) println | |
125 my_arr get(0, 1) println | |
126 my_arr get(0, 0) println | |
127 my_arr get(5, 5) println | |
128 | |
129 | |
130 | |
131 # 4) final piece | |
92 list(1, 2, 3, "foo") myAverage | 132 list(1, 2, 3, "foo") myAverage |