Advertisement
Guest User

Untitled

a guest
Feb 27th, 2017
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.20 KB | None | 0 0
  1. -- Let's figure out how lists work!
  2.  
  3. {- Lists are similarly said to be _polymorphic_, as the Maybe datatype was,
  4. because of this a right here
  5. |
  6. V -}
  7. data List a = Cons a (List a) | Nil deriving (Show, Eq)
  8. {- ^-- 1. --^ ^- 2.
  9. 1. Cons is a function that takes a value of type `a` and a value of type `List a` and returns a `List a`
  10. 2. Is our identity or basis list: the empty list.
  11.  
  12. Example:
  13. Cons 1 (Cons 2 Nil) is the same as [1,2] in normal haskell syntax
  14. -}
  15.  
  16. -- Exercise 1.
  17. -- Lists are functors so let's start by defining `fmap` as before
  18. instance Functor List where
  19. fmap f Nil = Nil
  20. fmap f (Cons a b) = Cons (f a) (fmap f b)
  21.  
  22. -- Exercise 2.
  23. -- Lists can be concatenated and added onto from the head
  24. -- Fill in the definitions of these functions so that they work as described
  25.  
  26. -- Hint: prepend 1 Nil == ?
  27. prepend :: a -> List a -> List a
  28. prepend a (Cons b c) = Cons a (Cons b c)
  29.  
  30. -- Hint: concat (Cons 1 Nil) (Cons 2 Nil) == ?
  31. concat :: List a -> List a -> List a
  32. concat Nil a = a
  33. concat (Cons a b) c = Cons a (concat b c)
  34.  
  35. main = (print $ concat (Cons 1 (Cons 2 (Cons 3 Nil))) (Cons 4 (Cons 5 Nil))) >>
  36. (print $ prepend 3 (Cons 2 (Cons 1 (Cons 0 Nil))))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement