Haskell fmap functor

≯℡__Kan透↙ 提交于 2019-12-09 01:15:29

Your Functor instance definition is non-exhaustive because it doesn't handle all possible type constructors of DQueue. Namely, it is missing a pattern matching Empty. You need to define how to handle fmap when your value is Empty.

The error speaks for itself: your definition for Functor is defined as:

data DQueue a = Empty | Enqueue a (DQueue a) deriving (Eq, Show, Read)

instance Functor DQueue where
    fmap f (Enqueue x xs) = Enqueue (f x) $ fmap f xs

There is however the possibility (in this case, if I understand your data-structure correctly, the certainty) that eventually fmap will be fed an Empty instance. You thus have to expand your definition to:

instance Functor DQueue where
    fmap f (Enqueue x xs) = Enqueue (f x) $ fmap f xs
    fmap _ Empty = Empty

Most compilers support a flag such that the compiler complains about non-exhaustive patterns, for the Glasgow Haskell Compiler (ghc), you can use the -fwarn-incomplete-patterns flag. For example:

$ ghc queue.hs -fwarn-incomplete-patterns
[1 of 1] Compiling Main             ( queue.hs, queue.o )

queue.hs:7:5: Warning:
    Pattern match(es) are non-exhaustive
    In an equation for ‘fmap’: Patterns not matched: _ Empty
Linking queue ...
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!