简体   繁体   中英

How to handle a list of custom datatype in haskell?

I know that I can operate with lists in haskell like tihs:

    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  

But what if I have a custom data class human ?

data Human = Human String Int

I tried

areAllAdults :: [Human] -> Bool
areAllAdults (Human name age):xs=age>21&&areAllAdults xs
...

But I get an error. What's the correct way to do this?

You were quite close, you can recurse with:

areAllAdults :: [Human] -> Bool
areAllAdults (Human name age : xs) = age > 21 && areAllAdults x
areAllAdults [] = True

But it makes more sense to work with all :

areAllAdults :: [Human] -> Bool
areAllAdults = all (\(Human _ age) -> age > 21)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM