Mike said: While I prefer this:
int minimumIntegerInBox (Collection<Box> boxes) {
int result = Integer.MAX_VALUE;
for (Box box : boxes) {
if (box.get() instanceof Integer) {
result = Math.min (result, Integer.class.cast (box.get()));
}
}
return result;
}
that would be cheating.It isn't cheating, but it isn't answering the question I posed, either. It's more or less the obvious thing to do in Java or Lisp. But conceptually it is pretty primitive. I don't care about the machinery involved in traversing a list (the looping construct). I want to take a binary operation like
Math.min and make it n-ary.Mike gave a very complete solution, but I'm only going to reformat the relevant part:
public static int minimumIntegerInBox(Collection<Box> boxes) {
Iterable<Box> intBoxes =
filter (boxes,
new Function<Box, Boolean>() {
@Override
public Boolean of(Box domainItem) {
return domainItem.get() instanceof Integer;
}
});
Iterable ints =
map (intBoxes,
new Function<Box, Integer>() {
@Override
public Integer of(Box domainItem) {
return Integer.class.cast(domainItem.get());
}
});
return minimumElement(ints);
}
public static int minimumElement(Iterable items) {
return best(
new Function<Pair, Boolean>() {
@Override
public Boolean of(Pair domainItem) {
return domainItem.second() < domainItem.first();
}
},
items);
}
That's a lot closer to what I had in mind, but these are untyped Boxes. I want to use parameterized Boxes.
1 comment:
Actually, my boxes were typed, but it looks like blogger decided that all the generic types were HTML tags and dropped them. Since I can't figure out how to post formatted code, I'll mail it to you.
Post a Comment