我知道我可以像这样在haskell中操作列表:
quicksort :: (Ord a) => [a] -> [a]
quicksort [] = []
quicksort (x:xs) =
let smallerSorted = quicksort [a | a <- xs, a <= x]
biggerSorted = quicksort [a | a <- xs, a > x]
in smallerSorted ++ [x] ++ biggerSorted
但是如果我有一个自定义数据类human
呢?
data Human = Human String Int
我试着
areAllAdults :: [Human] -> Bool
areAllAdults (Human name age):xs=age>21&&areAllAdults xs
...
但是我得到一个错误。正确的做法是什么?
你已经很接近了,你可以递归使用:
areAllAdults :: [Human] -> Bool
areAllAdults (Human name age : xs) = age > 21 && areAllAdults x
areAllAdults [] = True
但是使用all
更有意义:
areAllAdults :: [Human] -> Bool
areAllAdults = all ((Human _ age) -> age > 21)