haskell1.hs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. module Haskell1 where
  2. ones = 1 : ones
  3. fib = 1 : 1 : [a+b | (a,b) <- zip fib (tail fib)]
  4. mytake 0 _ = []
  5. mytake _ [] = []
  6. mytake n (x:xs) = x : mytake (n-1) xs
  7. myfoldl f z [] = z
  8. myfoldl f z (x:xs) = myfoldl f (f x z) xs
  9. instance Show (a -> b) where
  10. show f = "<< a function>>"
  11. -- define my-lenght
  12. mylenght :: [a] -> Int
  13. mylenght [] = 0
  14. mylenght (x:xs) = 1 + mylenght xs
  15. myrange :: Int -> Int -> [Int]
  16. myrange a b = if a > b
  17. then error "Low > High"
  18. else if a < b
  19. then a : myrange (a +1) b
  20. else [a]
  21. data TrafficLight = Red | Yellow | Green
  22. data Answer = Yes | No
  23. data Tree a = EmptyTree | Node a (Tree a) (Tree a)
  24. data Person = Person { firstname :: String
  25. , lastname :: String
  26. , age :: Int
  27. , height :: Float
  28. , phonenumber :: String
  29. }
  30. mymap :: (a -> b) -> [a] -> [b]
  31. mymap _ [] = []
  32. mymap f (x:xs) = f x : mymap f xs
  33. -- Re-write the myrange with boolean guards
  34. myrange2 :: Int -> Int -> [Int]
  35. myrange2 a b
  36. | a > b = error "low > high"
  37. | a == b = [b]
  38. | a < b = a : myrange2 (a + 1) b
  39. -- define myrange with only one input parameter
  40. myrange3 :: Int -> [Int]
  41. myrange3 a = a : myrange3 (a + 1)
  42. --describe the type of a list
  43. describelist :: [a] -> String
  44. describelist xs = "The list is " ++ case xs of
  45. [] -> "Empty List"
  46. [x] -> "One element / Singleton"
  47. xs -> "Multiple Elements"
  48. --definition of confitional take from list
  49. myTakeWhile :: (a -> Bool) -> [a] -> [a]
  50. myTakeWhile _ [] = []
  51. myTakeWhile f (x:xs)
  52. | f x = x : myTakeWhile f xs
  53. | otherwise = []
  54. myFilter :: (a -> Bool) -> [a] -> [a]
  55. myFilter _ [] = []
  56. myFilter c (x:xs)
  57. | c x = x : myFilter c xs
  58. | otherwise = myFilter c xs
  59. --define myReverse
  60. myReverse :: [a] -> [a]
  61. myReverse = foldl (\acc x -> x:acc) []
  62. --define mySum, a function that sums all the elements of a list
  63. mySum :: [Int] -> Int
  64. mySum [] = 0
  65. mySum (x:xs) = x + mySum xs
  66. mySum2 :: (Num a)=>[a] -> a
  67. mySum2 = foldl (\acc x -> acc + x) 0
  68. --define myFilter2 using foldr
  69. myFilter2 :: (a -> Bool) -> [a] -> [a]
  70. myFilter2 f = foldr (\x acc -> if f x then x:acc else acc) []