Is this a Functor or Monad?

前端 未结 3 1476
孤街浪徒
孤街浪徒 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:55

    Yes, it is a monad. The easiest way to see this is observing Promise f a ≅ Maybe (Either f a), thus it's also isomorphic to the transformer equivalent which has an already-proven standard monad instance.

    type Promise' f = ErrorT f Maybe
    
    promise2Trafo :: Promise f a -> Promise' f a
    promise2Trafo (PendingPromise f) = ErrorT . Just $ Left f
    promise2Trafo (ResolvedPromise a) = ErrorT . Just $ Right a
    promise2Trafo BrokenPromise = ErrorT Nothing
    
    trafo2Promise :: Promise' f a -> Promise f a
    trafo2Promise = ... -- straightforward inverse of `promise2Trafo`
    
    instance Applicative Promise where
      pure = trafo2Promise . pure
      fp <*> xp = trafo2Promise $ promise2Trafo fp <*> promise2Trafo xp
    

    and so on.

提交回复
热议问题