I need to implement code to cover few tests but I am stucked with few small problems.
The logic for foldr functions seem to be correct but I get an error during compiling.
This error means that my code does not cover some cases for foldr functions.
The code is given below:
module QueueFunctor where
import Test.HUnit (runTestTT,Test(TestLabel,TestList,TestCase),(~?=))
import Data.Char (toUpper)
import Prelude hiding (foldr)
import Data.Foldable (Foldable, foldr)
data DQueue a = Empty | Enqueue a (DQueue a)
deriving (Eq, Show, Read)
instance Functor DQueue
where
fmap f (Enqueue x xs) = (length xs == 0) then Empty else Enqueue (f x) $ fmap f xs
instance Foldable DQueue
where
foldr f result (Enqueue x xs) = if (length xs == 0) then f result Empty else foldr f (f x result) xs
-- | Tests a few examples.
main :: IO ()
main = do
testresults <- runTestTT tests
print testresults
sample1 :: DQueue Int
sample1 = Enqueue 1 $ Enqueue 2 $ Enqueue 3 $ Enqueue 4 Empty
sample2 :: DQueue String
sample2 = Enqueue "a" $ Enqueue "b" $ Enqueue "c" $ Enqueue "d" Empty
sample3 :: DQueue [Int]
sample3 = Enqueue [1,2,3] $ Enqueue [4,5,6] Empty
tests :: Test
tests = TestLabel "DQueueTest" (TestList [
fmap (+1) sample1 ~?= Enqueue 2 (Enqueue 3 (Enqueue 4 (Enqueue 5 Empty))),
fmap (map toUpper) sample2 ~?= Enqueue "A" (Enqueue "B" (Enqueue "C" (Enqueue "D" Empty))),
fmap (length) sample3 ~?= Enqueue 3 (Enqueue 3 Empty),
foldr (+) 0 sample1 ~?= 10,
foldr (++) "" sample2 ~?= "abcd",
foldr (\a b ->(+) b (length a)) 0 sample3 ~?= 6
])
Thank you in advance
Both instance declarations for Foldable
and Functor
are missing patterns that match the Empty
constructor.
You'll need to add code for
foldr f result Empty = ...
-- and ...
fmap f Empty = ...
Non-exhaustive means that there are patterns which are unmatched which can cause your program to crash.