Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- --(C) 2018, Functional Programming Course at University of Koblenz-Landau.
- module Fancy where
- import Test.HUnit (runTestTT,Test(TestLabel,TestList),(~?=))
- import Data.Char
- -- An 'arbitrary' datastructure that consists of two stack-like parts
- data FancyPart a = Add a (FancyPart a)| End deriving (Show,Eq)
- data Fancy a = Fancy (FancyPart a) (FancyPart a) deriving (Show,Eq)
- -- Implement fmap for the datastructure Fancy
- instance Functor Fancy
- where
- fmap f (Fancy a b) = Fancy (fmap f a) (fmap f b)
- instance Functor FancyPart
- where
- fmap f (Add a rest) = Add (f a) (fmap f rest)
- fmap f (End) = End
- -- Implement foldr for the datastructure Fancy
- instance Foldable Fancy
- where
- foldr f z (Fancy a b) = (foldr f (foldr f z b) a)
- instance Foldable FancyPart
- where
- foldr f z (Add a rest) = (f a (foldr f z rest))
- foldr f z (End) = z
- -- Here are two samples for testing later
- sample1 :: Fancy Int
- sample1 = Fancy (Add 3 $ Add 4 $ Add 5 $ Add 6 End)
- (Add 9 $ Add 8 $ Add 7 End)
- sample1' = Fancy (Add 4 $ Add 5 $ Add 6 $ Add 7 End)
- (Add 10 $ Add 9 $ Add 8 End)
- sample2 :: Fancy String
- sample2 = Fancy (Add "I" $ Add "want" $ Add "to" End)
- (Add "programmer" $ Add "a" $ Add "be" End)
- sample2' = Fancy (Add "I" $ Add "WANT" $ Add "TO" End)
- (Add "PROGRAMMER" $ Add "A" $ Add "BE" End)
- -- | Tests 'permutations' on a few examples.
- main :: IO ()
- main = do
- testresults <- runTestTT tests
- print testresults
- -- | A few tests for 'permutations'.
- tests :: Test
- tests = TestLabel "Fancy" (TestList [
- fmap (+1) sample1 ~?= sample1',
- fmap (map toUpper) sample2 ~?= sample2',
- foldr (+) 0 sample1 ~?= 42,
- foldr (\s1 s2 -> s1 ++ " " ++ s2) "" sample2 ~?= "I want to programmer a be ",
- fmap ((flip mod) 2) sample1 ~?= Fancy (Add 1 $ Add 0 $ Add 1 $ Add 0 End)
- (Add 1 $ Add 0 $ Add 1 End)
- ])
Add Comment
Please, Sign In to add comment