16 points · by joeyespo · 12y ago · 15 comments
data Node = Elephant | Box [Node]
count Elephant = 1
count (Box nodes) = sum (map count nodes)The Haskell implementation starts to get more complicated when you want to be able to define additional participants in the role of 'Node' without the original implementation having to know the name or structure of those participants. That's extremely common in game programming, for example.
If we need to support other operations as well, Haskell is perfectly capable of expressing the usual extensible OO solution, by using a record of functions. (A record type containing functions in FP is basically the same as an interface type in OO, and instances of that record type correspond to implementations of the interface.)
I'm certainly no expert in pure FP so there may be something I'm missing, but if the operations have to produce a change in the state of an entity, each one of the functions would have to both receive and return a state, right? Or you use a record of closures, each which returns a new record of closures?
It seems to me that in both cases you're discarding a lot of the benefits of Haskell's type system.
I think the tradeoff between adding methods to a class hierarchy and adding cases to functions is relevant here (I think this is known as the expression problem -- http://en.wikipedia.org/wiki/Expression_problem -- but I'm not sure), but it's not mentioned:
> Now the kind_of? test in num_elephants is a smell, since we should be wary of any conditional that tests the type of an object.
And, since it's ruby, the answer to "how can I put things other than Elephants in boxes", with the current code example, is "just make sure they have a #num_elephants method". Which, yeah, seems kind of insane, although part of that is the artificial example.
An IMO better solution still within this kind of OO world would be to declare an interface of some kind "CountableNode" or something, and say, anything you put in a box has to implement that interface (which to begin with has one method, #num_elephants). There are ways to do that sort of thing in ruby (there are ways to do almost anything in ruby), but they aren't done very often in rubyland, which I do think is a failing in the ruby idiom. Although many rubyists will say they've never found it a problem in practice (maybe they're right, maybe they just didn't recognize the root of the problems they did have).
Anyway, you make reasonable points even with these 'corrections', but Fowler could have made his example a bit tighter while still staying firmly within conventional ruby and/or OO best practices.
http://sourcemaking.com/refactoring/replace-conditional-with...
def num_elephants
result = 0
@children.each do |c|
if c.respond_to? :num_elephants
result += c.num_elephants
else
result += 1
end
end
return result
end
Personally, I just wouldn't mix my boxes with my elephants :)