私はいくつかのテストをカバーするためにコードを実装する必要がありますが、私はいくつかの小さな問題を抱えています。代数的データ構造のための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
])
はFoldable
とFunctor
のための両方のインスタンス宣言がEmpty
コンストラクタに一致するパターンが欠落している、事前に
[Haskell fmap functor](http://stackoverflow.com/questions/37987890/haskell-fmap-functor)の可能な複製 - 数時間前にこの質問をしました。 –
更新されたエラーメッセージで回答を受け取った後は、質問を変更しないでください。新しい質問を始めるのが最善でしょう。それが現れても、現在の答えは質問を読むことさえしないように見えます。 –
さて、私は新しいものを作ります。ごめんなさい。 –