Advertisement
VladNitu

W2L1(Lecture3)-FP24-Vlad-Batch2Q3-WL

Feb 18th, 2024
1,551
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import Prelude hiding (map, filter, all, any, takeWhile, dropWhile)
  2.  
  3. map :: (a -> b) -> [a] -> [b]
  4. -- List comprehension
  5. map f xs = [f x | x <- xs]
  6.  
  7. filter :: (a -> Bool) -> [a] -> [a]
  8. -- Explicit recursion
  9. filter p [] = []
  10. filter p (x : xs)
  11.   | p x = (x : filter p xs)
  12.   | otherwise =  filter p xs
  13.  
  14. all :: (a -> Bool) -> [a] -> Bool
  15. -- Using the library function foldr
  16. all p xs = foldr (\x acc -> (p x) && acc) True xs
  17. -- Using recursion
  18. all p [] = True
  19. all p (x : xs)
  20.   | p x = all p xs
  21.   | otherwise = False
  22.    
  23. any :: (a -> Bool) -> [a] -> Bool
  24. -- Using the library function foldr
  25. any p xs = foldr (\x acc -> (p x) || acc) False xs
  26. -- TODO: Using explicit recursion
  27. any p [] = False -- At least (>=) 1 element must be `p x`
  28. any p (x : xs)
  29.   | p x = True
  30.   | otherwise = any p xs
  31.  
  32. -- TODO: Using list comprehension
  33.  
  34.  
  35. takeWhile :: (a -> Bool) -> [a] -> [a]
  36. -- Explicit recursion
  37. takeWhile p [] = []
  38. takeWhile p (x : xs)
  39.   | p x = x : takeWhile p xs
  40.   | otherwise = []
  41.  
  42. dropWhile :: (a -> Bool) -> [a] -> [a]
  43. -- Explicit recursion
  44. dropWhile p [] = []
  45. dropWhile p (x : xs)
  46.   | p x = dropWhile p xs -- drop
  47.   | otherwise = (x : xs)
  48. -- TODO: Using foldr
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement