假设我有以下内容:
class Shape a where
draw a :: a -> IO ()
data Rectangle = Rectangle Int Int
instance Shape Rectangle where
draw (Rectangle length width) = ...
data Circle = Circle Int Int
instance Shape Circle where
draw (Circle center radius) = ...
Run Code Online (Sandbox Code Playgroud)
有没有办法让我定义一个形状列表,遍历列表,并在每个形状上调用绘图函数?以下代码将无法编译,因为列表元素的类型不同:
shapes = [(Circle 5 10), (Circle 20, 30), (Rectangle 10 15)]
Run Code Online (Sandbox Code Playgroud)
我知道我正在以OO的方式思考并尝试将其应用于Haskell,这可能不是最好的方法.对于需要处理不同类型对象集合的程序,最好的Haskell方法是什么?
本着问题中其他常见错误的精神,Haskell程序员最常犯的错误是什么?我一直在教自己Haskell一段时间,我开始对语言感到很自在,开始在现实世界中应用它.