2

假设我有两个这样的功能:

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

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

WhereCatDogare 都是Eatables。

所以我可以这样调用食物函数:

let cat = food "cat" :: Cat

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

let cat = food :: Cat
4

1 回答 1

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
于 2013-06-06T06:34:23.020 回答