I create my own data type, and try to implement functor method as follow:
data Hieu a = Hieu [a] deriving (Show, Read, Eq)
instance Functor Hieu where
fmap f (Hieu [x]) = Hieu (f [x])
It’s very simple piece of code but it failed. Can you explain why?
Thanks for all your responses. Now I understand that I apply functor only for one case. I tried to rewrite as follow, without using map
data Hieu a = Hieu [a] deriving (Show, Read, Eq)
consHieu :: a -> (Hieu a) -> (Hieu a)
consHieu x (Hieu xs) = Hieu (x:xs)
instance Functor Hieu where
fmap f (Hieu (x:xs)) = consHieu (f x) (fmap f (Hieu xs))
fmap f (Hieu []) = Hieu []
Thanks for all your responses. Now I understand that I apply functor only for one case. I tried to rewrite as follow, without using map
data Hieu a = Hieu [a] deriving (Show, Read, Eq)
consHieu :: a -> (Hieu a) -> (Hieu a)
consHieu x (Hieu xs) = Hieu (x:xs)
instance Functor Hieu where
fmap f (Hieu (x:xs)) = consHieu (f x) (fmap f (Hieu xs))
fmap f (Hieu []) = Hieu []
In the expression
f [x]you’re applyingfto a list, but that’s not allowed since the type signature offmapis(a -> b) -> Hieu a -> Hieu b. You’re not allowed to restrictfto[a] -> [b].Perhaps you meant to write
This would compile, but it would only work if the list has exactly one element. The normal way of making
Hieua functor would be to usemapto apply the function to all of the elements like so: