List.agda 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. module Data.List where
  2. import Prelude
  3. import Data.Nat
  4. import Data.Tuple
  5. open Prelude
  6. open Data.Nat
  7. open Data.Tuple
  8. infixr 50 _::_ _++_
  9. data List (A : Set) : Set where
  10. [] : List A
  11. _::_ : A -> List A -> List A
  12. {-# BUILTIN LIST List #-}
  13. {-# BUILTIN NIL [] #-}
  14. {-# BUILTIN CONS _::_ #-}
  15. length : {A : Set} -> List A -> Nat
  16. length [] = 0
  17. length (_ :: xs) = 1 + length xs
  18. map : {A B : Set} -> (A -> B) -> List A -> List B
  19. map f [] = []
  20. map f (x :: xs) = f x :: map f xs
  21. _++_ : {A : Set} -> List A -> List A -> List A
  22. [] ++ ys = ys
  23. (x :: xs) ++ ys = x :: (xs ++ ys)
  24. zipWith : {A B C : Set} -> (A -> B -> C) -> List A -> List B -> List C
  25. zipWith f [] [] = []
  26. zipWith f (x :: xs) (y :: ys) = f x y :: zipWith f xs ys
  27. zipWith f [] (_ :: _) = []
  28. zipWith f (_ :: _) [] = []
  29. foldr : {A B : Set} -> (A -> B -> B) -> B -> List A -> B
  30. foldr f z [] = z
  31. foldr f z (x :: xs) = f x (foldr f z xs)
  32. foldl : {A B : Set} -> (B -> A -> B) -> B -> List A -> B
  33. foldl f z [] = z
  34. foldl f z (x :: xs) = foldl f (f z x) xs
  35. replicate : {A : Set} -> Nat -> A -> List A
  36. replicate zero x = []
  37. replicate (suc n) x = x :: replicate n x
  38. iterate : {A : Set} -> Nat -> (A -> A) -> A -> List A
  39. iterate zero f x = []
  40. iterate (suc n) f x = x :: iterate n f (f x)
  41. splitAt : {A : Set} -> Nat -> List A -> List A × List A
  42. splitAt zero xs = < [] , xs >
  43. splitAt (suc n) [] = < [] , [] >
  44. splitAt (suc n) (x :: xs) = add x $ splitAt n xs
  45. where
  46. add : _ -> List _ × List _ -> List _ × List _
  47. add x < ys , zs > = < x :: ys , zs >
  48. reverse : {A : Set} -> List A -> List A
  49. reverse xs = foldl (flip _::_) [] xs