2016-06-23 19 views
-3

私はいくつかのテストをカバーするためにコードを実装する必要がありますが、私はいくつかの小さな問題を抱えています。代数的データ構造のためのHaskell fmap foldr

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 Functor DQueue 
     where 
     fmap f (Enqueue x xs) = (length xs == 0) then Empty else Enqueue (f x) $ fmap f xs 

instance Foldable DQueue 
    where 
    foldr f result (Enqueue x xs) = if (length xs == 0) then f result Empty else 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 

sample3 :: DQueue [Int] 
sample3 = Enqueue [1,2,3] $ Enqueue [4,5,6] Empty 

tests :: Test 
tests = TestLabel "DQueueTest" (TestList [ 
     fmap (+1) sample1 ~?= Enqueue 2 (Enqueue 3 (Enqueue 4 (Enqueue 5 Empty))), 
     fmap (map toUpper) sample2 ~?= Enqueue "A" (Enqueue "B" (Enqueue "C" (Enqueue "D" Empty))), 
     fmap (length) sample3 ~?= Enqueue 3 (Enqueue 3 Empty), 
     foldr (+) 0 sample1 ~?= 10, 
     foldr (++) "" sample2 ~?= "abcd", 
     foldr (\a b ->(+) b (length a)) 0 sample3 ~?= 6 
    ]) 

FoldableFunctorのための両方のインスタンス宣言がEmptyコンストラクタに一致するパターンが欠落している、事前に

+3

[Haskell fmap functor](http://stackoverflow.com/questions/37987890/haskell-fmap-functor)の可能な複製 - 数時間前にこの質問をしました。 –

+2

更新されたエラーメッセージで回答を受け取った後は、質問を変更しないでください。新しい質問を始めるのが最善でしょう。それが現れても、現在の答えは質問を読むことさえしないように見えます。 –

+0

さて、私は新しいものを作ります。ごめんなさい。 –

答えて

2

、ありがとうございました。あなたは

foldr f result Empty = ... 
-- and ... 
fmap f Empty = ... 

非網羅用のコードを追加する必要があります

は、プログラムがクラッシュする可能性があります追随を許さないパターンがあることを意味しています。

+0

あなたは正しいです、それはfmapで問題を解決しましたが、foldrでは解決しませんでした。 –

+0

'' Nothing'コンストラクタに '' foldr'を実装する方法を見てください(http://hackage.haskell.org/package/base-4.9.0.0/docs/src/Data.Foldable.html) 。あなたの実装はおそらく同様に見えます。 –

関連する問題