oop – 如何在Haskell中建模类层次结构?

我是C#开发人员。来自世界OO方面,我从接口,类和类型层次的角度开始思考。由于Haskell中缺少OO,有时候我发现自己陷入困境,我无法想像用Haskell模拟某些问题的方法。

在Haskell中如何建模涉及类层次结构的现实世界,如下所示:http://www.braindelay.com/danielbray/endangered-object-oriented-programming/isHierarchy-4.gif

让我们假设以下操作:人类可以说,狗可以吠叫,如果一个物种的性别相反,一个物种的所有成员都可以与同一物种的成员交配。我将在这个haskell中定义这样:

data Gender = Male | Female deriving Eq

class Species s where
    gender :: s -> Gender

-- Returns true if s1 and s2 can conceive offspring
matable :: Species a => a -> a -> Bool
matable s1 s2 = gender s1 /= gender s2

data Human = Man | Woman
data Canine = Dog | Bitch

instance Species Human where
    gender Man = Male
    gender Woman = Female

instance Species Canine where
    gender Dog = Male
    gender Bitch = Female

bark Dog = "woof"
bark Bitch = "wow"

speak Man s = "The man says " ++ s
speak Woman s = "The woman says " ++ s

现在,可操作的操作具有类型Species s => s – > s – > Bool,树皮有Canine – >字符串和说话有人类 – >字符串 – >串。

我不知道这是否有帮助,但鉴于这个问题的抽象性质,这是我能想到的最好的。

编辑:回应丹尼尔的评论:

集合的简单层次结构可能看起来像这样(忽略已经存在的类,如Foldable和Functor):

class Foldable f where
    fold :: (a -> b -> a) -> a -> f b -> a

class Foldable m => Collection m where
    cmap :: (a -> b) -> m a -> m b
    cfilter :: (a -> Bool) -> m a -> m a

class Indexable i where
    atIndex :: i a -> Int -> a

instance Foldable [] where
    fold = foldl

instance Collection [] where
    cmap = map
    cfilter = filter

instance Indexable [] where
    atIndex = (!!)

sumOfEvenElements :: (Integral a, Collection c) => c a -> a
sumOfEvenElements c = fold (+) 0 (cfilter even c)

现在,sumOfEvenElements采取任何种类的积分收集,并返回该集合的所有偶数元素的总和。

翻译自:https://stackoverflow.com/questions/3124511/how-to-model-class-hierarchies-in-haskell

转载注明原文:oop – 如何在Haskell中建模类层次结构?