[Haskell-beginners] Functor instance

Francesco Ariis fa-ml at ariis.it
Sat Mar 3 21:40:43 UTC 2018


Hello Hilco,

On Sat, Mar 03, 2018 at 12:32:34PM -0800, Hilco Wijbenga wrote:
> data Result failure success
>     = Success success
>     | Failure failure
> 
> instance Functor (Result failure) where
>     fmap f (Success value) = Success (f value)
>     fmap _ (Failure error) = Failure error
>     -- fmap _ result@(Failure error) = result
>     -- fmap _ result          = result
> 
> 1) Is it possible to define "Result" as "Result success failure"
> (instead of "Result failure success") and _still_ create an instance
> of Functor?

Yes, as far the compiler is concerned `data Result failure success`
is equivalent to `data Result a b`. Same in your instance, you could
have written:

    instance Functor (Result a) where
        -- etc.

no problem.

> 2) The two alternatives for fmap for the Failure scenario do not
> compile (the end result is "Result failure a" instead of "Result
> failure b") and that makes sense. But I would like to be able to
> express that "result" is not touched. Is there any way to do that?

You can but you have to modify your datatype! Probably you want
something like this:

    data Result r f = Result r (ResState e)
    data ResState e = Ok | Error e


> 3) And while wondering about that, is GHC smart enough to realize that
> "= Failure error" in the failure scenario is actually a NOP? (I'm just
> curious.)

Not sure about this one, but I strongly suspect so!

Was the explanation clear?
-F


More information about the Beginners mailing list