Home > Blockchain >  How to handle a list of custom datatype in haskell?
How to handle a list of custom datatype in haskell?

Time:01-17

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?

CodePudding user response:

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)
  • Related