Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/scala/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Haskell foldr algrebraic数据类型_Haskell_Algebraic Data Types - Fatal编程技术网

Haskell foldr algrebraic数据类型

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

我已经解决了所有关于函数的问题,但还有一个问题

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)