2016-06-23 10 views
1

私は関数で持っていたすべての問題を解決しましたが、残っています。Haskell foldr algrebraicのデータ型

foldr関数は、最初の1に最後の要素から動作し、私はプログラムをコンパイルするとき

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

が、私は1つのエラーに関するテストを取得、他の順序でデータを取得する必要があります:

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

ありがとうございます。

+0

なぜ「foldl」を使用しないのですか? – karakfa

+0

foldrを使用するタスクの記述には厳しい規則がありました。 –

+2

あなたの 'foldr'定義は実際に' foldl'のように見えます。それは逆の結果を説明するでしょう。 – melpomene

答えて

2

Foldableのリストインスタンスに使用されるこの定義をリストの場合はfoldrと考えてください。

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) 
+0

私はそれをありがとう! –