Re:The visitor pattern is essentially the same thing as Chur...
by mdoms on Thursday February 04, 2021 @01:12PM
(#26028101)
So every shape now has to reference every other shape? If I want to add a new shape I not only have to define the shape function,
and update the area function, I also need to update every existing type like
Am I understanding this correctly? How is this a win? What if I have a hundred different shapes, now every shape definition is just a list of a hundred parameters and hopefully I called the correct one in my copy&paste-fest.
[ Parent
| on HN ]
Re:The visitor pattern is essentially the same thing as Chur...
by Twisol on Thursday February 04, 2021 @01:37PM
(#26028372)
That's why we usually group all of these handlers into a single Visitor interface. Then you only add one class and one extra method to the Visitor, and all the other variants stay the same.
You're brushing up against the so-called "expression problem", though, where you can choose between adding types easily or adding algorithms easily, but not usually both.
Re:The visitor pattern is essentially the same thing as Chur...
by h_anna_h on Thursday February 04, 2021 @03:26PM
(#26029394)
Here you go
import math
def Circle(x, y, r):
return (lambda d : d['visitCircle'](x, y, r))
def Rectangle(x, y, w, h):
return (lambda d : d['visitRectangle'](x, y, w, h))
def area(shape):
return shape({
'visitCircle': lambda x, y, r : math.pi * r * r,
'visitRectangle': lambda x, y, w, h : w * h
})
exampleCircle = Circle(2, 1.4, 4.5)
exampleRectangle = Rectangle(1.3, 3.1, 10.3, 7.7)
print(area(exampleCircle))
print(area(exampleRectangle))
# 63.61725123519331
# 79.31
Re:The visitor pattern is essentially the same thing as Chur...
by mdoms on Thursday February 04, 2021 @04:45PM
(#26030159)
At this point I have to believe you functional programming guys are just taking the piss.
Re:The visitor pattern is essentially the same thing as Chur...
by h_anna_h on Thursday February 04, 2021 @06:45PM
(#26031162)
What do you mean? This solves the issue that you mentioned. I am not really a "functional programming guy" myself.