Is this a Functor or Monad?

前端 未结 3 1473
孤街浪徒
孤街浪徒 2021-01-12 18:17

I implemented my own Promise structure in C# and wanted to test the concept in Haskell so after some severe brain workouts (still very new to this) I produced



        
3条回答
  •  执笔经年
    2021-01-12 18:51

    What you'll want to do is try to implement the instance for Functor and check if it conforms to the Functor Laws. Start with the instance:

    instance Functor (Promise f) where
        fmap f (PendingPromise g) = PendingPromise g
        fmap f (ResolvedPromise a) = ResolvedPromise (f a)
        fmap f BrokenPromise = BrokenPromise
    

    Does this conform to the Functor Laws? Since the cases for PendingPromise and BrokenPromise are always the identity, I'll exclude them for brevity:

    -- fmap id = id
    fmap id (ResolvedPromise a) = ResolvedPromise (id a) = ResolvedPromise a
    
    -- fmap (f . g) = fmap f . fmap g
    fmap (f . g) (ResolvedPromise a) = ResolvedPromise (f (g a))
    fmap f (fmap g (ResolvedPromise a)) = fmap f (ResolvedPromise (g a)) = ResolvedPromise (f (g a))
    

    So yes, it does conform to the Functor laws.

    Next, see if you can write the Applicative and Monad instances and prove that they conform to the respective laws. If you can write an instance that does, then your data type is a Monad, irrespective of the Future class.

提交回复
热议问题