我怎样才能按名字对动物进行分类?名称由String
值表示.
data Animal = Cat String | Dog String | Fox String deriving (Show) testAnimals = [(Dog "c"),(Fox "a"),(Cat "b")] sortAnimalsByName :: [Animal] -> [Animal] sortAnimalsByName animals = undefined
查询:
sortAnimalsByName testAnimals
应该返回:
[(Fox "a"),(Cat "b"),(Dog "c")]
我认为,功能sort :: Ord a => [a] -> [a]
从Data.List
应使用,但如何?
首先,您最好定义一个animalName
函数:
animalName :: Animal -> String animalName (Cat n) = n animalName (Dog n) = n animalName (Fox n) = n
只需使用sortBy
其中比较简直是compare
但on
的animalName
:
import Data.Function(on) import Data.List(sortBy) sortAnimalsByName :: [Animal] -> [Animal] sortAnimalsByName = sortBy (compare `on` animalName)
或者你可以 - 像@JonPurdy建议的那样使用comparing
它基本上和以下相同on compare
:
import Data.Ord(comparing) sortAnimalsByName :: [Animal] -> [Animal] sortAnimalsByName = sortBy (comparing animalName)
甚至更短:
import Data.List(sortOn) sortAnimalsByName :: [Animal] -> [Animal] sortAnimalsByName = sortOn animalName
animalName
如果使用记录语法,还可以省略定义:
--omitting the `animalName` function data Animal = Cat { animalName :: String} | Dog { animalName :: String} | Fox { animalName :: String} deriving (Show)