假设我有两个这样的函数:
food :: Eatable a => String -> a
food animalType = getAnimal animalType
getAnimal :: Eatable a => String -> a
getAnimal "cat" = Cat
getAnimal "dog" = Dog
Cat
和Dog
都是Eatable
s。
所以我可以像这样调用食物功能:
let cat = food "cat" :: Cat
但是那里的字符串似乎是多余的。有没有办法将其改为:
let cat = food :: Cat
答案 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