繁体   English   中英

Haskell foldr代数数据类型

[英]Haskell foldr algrebraic datatypes

我已经解决了函数遇到的所有问题,但剩下一个。

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"
    ])

编译程序时,遇到关于测试的错误:

### Failure in: DQueueTest:1
QueueFunctors.hs:56
expected: "abcd"
 but got: "dcba"

先感谢您。

考虑一下列表的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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM