main :: IO() main = do print $ "Task 2" print $ Animal "Lion" 1 Carnivore 3 -- Lion(1,Carnivore,3) print $ updateDiet zoo 3 Herbivore -- [Lion(1,Carnivore,3),Elephant(2,Herbivore,3),Bear(3,Herbivore,6),Turtle(4,Herbivore,2)] print $ feedAnimal zoo 3 1 -- [Lion(1,Carnivore,6),Elephant(2,Herbivore,3),Bear(3,Omnivore,6),Turtle(4,Herbivore,2)] print $ feedIfHungry zoo 3 [1,2,3,4] -- [Lion(1,Carnivore,6),Elephant(2,Herbivore,6),Bear(3,Omnivore,6),Turtle(4,Herbivore,5)] print $ feedIfHungry zoo 3 [3] -- [Lion(1,Carnivore,3),Elephant(2,Herbivore,3),Bear(3,Omnivore,6),Turtle(4,Herbivore,2)] print $ findAnimalById zoo 10 -- Nothing print $ findAnimalById zoo 2 -- Just Elephant(2,Herbivore,3) where zoo = [ Animal "Lion" 1 Carnivore 3 , Animal "Elephant" 2 Herbivore 3 , Animal "Bear" 3 Omnivore 6 , Animal "Turtle" 4 Herbivore 2] type Species = String type AnimalId = Int data Diet = Herbivore | Carnivore | Omnivore deriving (Show, Eq) data Animal = Animal { species :: Species, animalId :: AnimalId, diet :: Diet, hungerLevel :: Int } deriving Eq instance Show Animal where show (Animal s id d hunger) = s ++ "(" ++ show id ++ "," ++ show d ++ "," ++ show hunger ++ ")" updateDiet :: [Animal] -> AnimalId -> Diet -> [Animal] updateDiet zoo id d = [if animalId a == id then a { diet = d } else a | a <- zoo] feedAnimal :: [Animal] -> Int -> AnimalId -> [Animal] feedAnimal zoo k id = map (\ a -> if animalId a == id then a { hungerLevel = hungerLevel a + k } else a) zoo feedIfHungry :: [Animal] -> Int -> [AnimalId] -> [Animal] feedIfHungry zoo k = foldr (\ id zoo -> if elem id hungryAnimals then feedAnimal zoo k id else zoo) zoo where hungryAnimals = [animalId a | a <- zoo, hungerLevel a < 5] findAnimalById :: [Animal] -> AnimalId -> Maybe Animal findAnimalById [] _ = Nothing findAnimalById (a:as) id = if animalId a == id then Just a else findAnimalById as id