Guest User

Untitled

a guest
Jun 25th, 2018
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.92 KB | None | 0 0
  1. --(C) 2018, Functional Programming Course at University of Koblenz-Landau.
  2. module Fancy where
  3.  
  4. import Test.HUnit (runTestTT,Test(TestLabel,TestList),(~?=))
  5. import Data.Char
  6.  
  7. -- An 'arbitrary' datastructure that consists of two stack-like parts
  8. data FancyPart a = Add a (FancyPart a)| End deriving (Show,Eq)
  9. data Fancy a = Fancy (FancyPart a) (FancyPart a) deriving (Show,Eq)
  10.  
  11. -- Implement fmap for the datastructure Fancy
  12. instance Functor Fancy
  13. where
  14. fmap f (Fancy a b) = Fancy (fmap f a) (fmap f b)
  15.  
  16. instance Functor FancyPart
  17. where
  18. fmap f (Add a rest) = Add (f a) (fmap f rest)
  19. fmap f (End) = End
  20.  
  21. -- Implement foldr for the datastructure Fancy
  22. instance Foldable Fancy
  23. where
  24. foldr f z (Fancy a b) = (foldr f (foldr f z b) a)
  25.  
  26. instance Foldable FancyPart
  27. where
  28. foldr f z (Add a rest) = (f a (foldr f z rest))
  29. foldr f z (End) = z
  30.  
  31.  
  32. -- Here are two samples for testing later
  33. sample1 :: Fancy Int
  34. sample1 = Fancy (Add 3 $ Add 4 $ Add 5 $ Add 6 End)
  35. (Add 9 $ Add 8 $ Add 7 End)
  36. sample1' = Fancy (Add 4 $ Add 5 $ Add 6 $ Add 7 End)
  37. (Add 10 $ Add 9 $ Add 8 End)
  38. sample2 :: Fancy String
  39. sample2 = Fancy (Add "I" $ Add "want" $ Add "to" End)
  40. (Add "programmer" $ Add "a" $ Add "be" End)
  41. sample2' = Fancy (Add "I" $ Add "WANT" $ Add "TO" End)
  42. (Add "PROGRAMMER" $ Add "A" $ Add "BE" End)
  43.  
  44. -- | Tests 'permutations' on a few examples.
  45. main :: IO ()
  46. main = do
  47. testresults <- runTestTT tests
  48. print testresults
  49.  
  50. -- | A few tests for 'permutations'.
  51. tests :: Test
  52. tests = TestLabel "Fancy" (TestList [
  53. fmap (+1) sample1 ~?= sample1',
  54. fmap (map toUpper) sample2 ~?= sample2',
  55. foldr (+) 0 sample1 ~?= 42,
  56. foldr (\s1 s2 -> s1 ++ " " ++ s2) "" sample2 ~?= "I want to programmer a be ",
  57. fmap ((flip mod) 2) sample1 ~?= Fancy (Add 1 $ Add 0 $ Add 1 $ Add 0 End)
  58. (Add 1 $ Add 0 $ Add 1 End)
  59. ])
Add Comment
Please, Sign In to add comment