Haskell foldr algrebraic数据类型
我已经解决了所有关于函数的问题,但还有一个问题 foldr函数从最后一个元素到第一个元素,我需要以另一个顺序获取数据Haskell foldr algrebraic数据类型,haskell,algebraic-data-types,Haskell,Algebraic Data Types,我已经解决了所有关于函数的问题,但还有一个问题 foldr函数从最后一个元素到第一个元素,我需要以另一个顺序获取数据 module QueueFunctor where import Test.HUnit (runTestTT,Test(TestLabel,TestList,TestCase),(~?=)) import Data.Char (toUpper) import Prelude hiding (foldr) import Data.Foldable (Foldable, foldr
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"
])
提前感谢。考虑列表的
foldr
定义,它用于Foldable
的列表实例
foldr :: (a -> b -> b) -> b -> [a] -> b
foldr _ z [] = z
foldr f z (x:xs) = f x (foldr f z xs)
现在考虑您的数据类型与列表同构。
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)
为什么不使用
foldl
?在任务描述中有一条严格的规则来使用foldr。您的foldr
定义看起来实际上是foldl
。这可以解释相反的结果。
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)