Is there an injection equivalent for Haskell in the context of free monads

I am trying to translate this Scala catsexample about creating free monads.

The essence of the example is the decomposition of individual problems into separate data types:

data Interact a = Ask (String -> a) | Tell String a deriving (Functor)

data DataOp = AddCat String | GetAllCats [String] deriving (Functor)

type CatsApp = Sum Interact DataOp

Without these two separate issues, I would construct a β€œlanguage” for operations Interactas follows:

ask :: Free Interact String
ask = liftF $ Ask id

tell :: String -> Free Interact ()
tell str = liftF $ Tell str ()

However, if I want to use askit tellin a program that also uses it DataOp, I cannot define them with the types indicated above, since such a program will have a type:

program :: Free CatsApp a

In catsto determine the operations telland askthey use the class InjectKand method injectfrom Free:

class Interacts[F[_]](implicit I: InjectK[Interact, F]) {
  def tell(msg: String): Free[F, Unit] = Free.inject[Interact, F](Tell(msg))
  def ask(prompt: String): Free[F, String] = Free.inject[Interact, F](Ask(prompt))
}

, , (DataOp , Interact ) ( ).

, Haskell?

+4
1

Γ  la carte. Scala Haskell. , , sup, "" sub:

class (Functor sub, Functor sup) => sub :-<: sup where
    inj :: sub a -> sup a

( Prism, .) functor, :-<: Sum,

instance Functor f => f :-<: f where
    inj = id
instance (Functor f, Functor g) => f :-<: (Sum f g) where
    inj = InL
instance (Functor f, Functor g, Functor h, f :-<: g) => f :-<: (Sum h g) where
    inj = InR . inj

, .

ask :: Interact :-<: f => Free f String
ask = liftF $ inj $ Ask id

tell :: Interact :-<: f => String -> Free f ()
tell str = liftF $ inj $ Tell str ()

addCat :: DataOp :-<: f => String -> Free f ()
addCat cat = liftF $ inj $ AddCat cat ()

getCats :: DataOp :-<: f => Free f [String]
getCats = liftF $ inj $ GetCats id

, Interact, DataOp, .

myProgram :: (Interact :-< f, DataOp :-< f) => Free f ()
myProgram = ask >>= addCat

, MTL-.

+2

Source: https://habr.com/ru/post/1689501/


All Articles