Thursday, December 18, 2014

7L7W Week 2: Io Day 2 round 2 continued>Toddling

I should probably check to see if something has defined the sum slot on Number and List first, but... let's start this simple.

Number sum := method(call target)
List sum := method(
total := 0;
foreach(val, total = total + val sum)
)

Io> a := list(list(1, 2, 3), list(1, 2, 3))
==> list(list(1, 2, 3), list(1, 2, 3))
Io> a sum
==> 12

As the title suggests, I think I'm getting used to this now. This may not be exactly how it should be done, but it was ridiculously easy to implement (even with accidental recursion >.> ). Implementing a sum method on two base prototypes of the language leaves me a touch uneasy but these are additions to the prototypes rather than redefinitions. If I were going to try this in production code of some sort I would need to either use a less generic slot name or properly check for an existing sum slot on both prototypes.
... Also it strikes me that the question was to write a program, not a method on the List prototype. Oh well. Nobody is grading this but me.

The averaging problem was pretty straightforward but I had some confusion around the select message. Mostly because I saw a reference in the programming guide to a method ISNUMBER() which doesn't appear to actually exist anywhere? Or at any rate I couldn't find it so I had to do this:

List myAverage := method(
values := call target select(v, v type == "Number");
if(values size == 0, Exception raise("No Number in target List"));
values reduce(+) / values size
)

Unlike the summing problem this solution will not handle multidimensional arrays. I could swap the reduce message for the sum method defined above but I'd have to handle n-dimensionality in the select message at the top of the method as well.

... I was going to finish day 2 today and post this. Actually I was hoping to post this yesterday but it has not been a very good week for side projects. Unfortunately it's going to have to wait. It might have to wait until the weekend. I want to get this posted at least and I'll try to get day 2 finished before Monday.

No comments: