Haskell 如何获取元组列表中两种不同数据类型之间的差异?
Haskell How to get the difference between 2 different data types in a list of tuples?
我想知道是否有一种简单的方法可以在元组列表中获得 Haskell 中两种数据类型之间的差异。
假设我定义了 2 种数据类型:
type Name = String
type Age = String
type Color = String
type Size = Int
data Animal = Animal Name Age Color Size
data Cat = Cat Name Age Color
然后,我想获得一个元组列表,其中包含除猫以外的所有动物。
该功能类似于:
getAnimalsButCats :: [Animal] -> [Cat] -> [(Name, Age, Color)]
getAnimalsButCats [(Animal name age color _)] [(Cat nameC ageC colorC)] = //diff between [Animal] and [Cat]
你可能想要这样的东西
type Name = String
type Age = String
type Color = String
type Size = Int
data AnimalKind = Cat | Dog | Horse | Bird
data Animal = Animal AnimalKind Name Age Color Size
getAnimalsButCats :: [Animal] -> [(Name, Age, Color)]
getAnimalsButCats [] = []
-- Skip cats
getAnimalsButCats ((Animal Cat _ _ _ _):xs) = getAnimalsButCats xs
-- Save name, age, color for any other animal
getAnimalsButCats ((Animal _ name age color _): xs) = (name, age, color) : (getAnimalsButCats xs)
我想知道是否有一种简单的方法可以在元组列表中获得 Haskell 中两种数据类型之间的差异。
假设我定义了 2 种数据类型:
type Name = String
type Age = String
type Color = String
type Size = Int
data Animal = Animal Name Age Color Size
data Cat = Cat Name Age Color
然后,我想获得一个元组列表,其中包含除猫以外的所有动物。 该功能类似于:
getAnimalsButCats :: [Animal] -> [Cat] -> [(Name, Age, Color)]
getAnimalsButCats [(Animal name age color _)] [(Cat nameC ageC colorC)] = //diff between [Animal] and [Cat]
你可能想要这样的东西
type Name = String
type Age = String
type Color = String
type Size = Int
data AnimalKind = Cat | Dog | Horse | Bird
data Animal = Animal AnimalKind Name Age Color Size
getAnimalsButCats :: [Animal] -> [(Name, Age, Color)]
getAnimalsButCats [] = []
-- Skip cats
getAnimalsButCats ((Animal Cat _ _ _ _):xs) = getAnimalsButCats xs
-- Save name, age, color for any other animal
getAnimalsButCats ((Animal _ name age color _): xs) = (name, age, color) : (getAnimalsButCats xs)