有没有办法在此函数中删除类型的冗余?

时间:2013-06-06 06:27:18

标签: haskell

假设我有两个这样的函数:

food :: Eatable a => String -> a
food animalType = getAnimal animalType

getAnimal :: Eatable a => String -> a
getAnimal "cat" = Cat
getAnimal "dog" = Dog

CatDog都是Eatable s。

所以我可以像这样调用食物功能:

let cat = food "cat" :: Cat

但是那里的字符串似乎是多余的。有没有办法将其改为:

let cat = food :: Cat

1 个答案:

答案 0 :(得分:5)

是的,只需删除多余的参数即可。返回类型getAnimal确定将使用的实例。

data Cat = Cat
data Dog = Dog

class Eatable animal where
  getAnimal :: animal

instance Eatable Dog where
  getAnimal = Dog

instance Eatable Cat where
  getAnimal = Cat