Is Haskell's pure
function the same as return
?
I just can make a type an instance of Monad if it is already an instance of Applicative, right? So I wonder that Applicative's pure
is everytime interchangeable with Monad's return
?
Is there an example where they are not the same?
data HelloType a = HelloType { getValue :: a } deriving (Show, Eq)
instance Functor HelloType where
fmap f (HelloType y) = HelloType (f y)
instance Applicative HelloType where
(<*>) (HelloType f) (HelloType x) = HelloType (f x)
pure = HelloType
instance Monad HelloType where
(>>=) (HelloType x) f = f x
-- return = pure
return = HelloType
plus3 :: (Num a) => Maybe a -> HelloType (Maybe a)
plus3 (Just x) = HelloType (Just $ x + 3)
plus3 Nothing = HelloType Nothing
main= do
let withPure = pure (Just 3) >>= plus3 >>= plus3
withReturn = return (Just 3) >>= plus3 >>= plus3
print $ withPure == withReturn -- TRUE