I have solved all issues I had with functions but one is left.
The foldr function works from last element to the first one and I need to get the data in the other order
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 Foldable DQueue
where
foldr _ result Empty = result
foldr f result (Enqueue x xs) = 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
tests :: Test
tests = TestLabel "DQueueTest" (TestList [
foldr (++) "" sample2 ~?= "abcd"
])
When I compile the program, I get one error regarding tests:
### Failure in: DQueueTest:1
QueueFunctors.hs:56
expected: "abcd"
but got: "dcba"
Thank you in advance.
Consider this definition of foldr
for lists, which is used for the list instance of Foldable
.
foldr :: (a -> b -> b) -> b -> [a] -> b
foldr _ z [] = z
foldr f z (x:xs) = f x (foldr f z xs)
Now consider that your data type is isomorphic to a list.
data DQueue a = Empty | Enqueue a (DQueue a)
toList :: Dqueue a -> [a]
toList Empty = []
toList (Enqueue x xs) = x : toList xs
fromList :: [a] -> Dqueue a
fromList [] = Empty
fromList (x:xs) = Enqueue x (fromList xs)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.