He estado tratando de envolver mi cabeza alrededor de las mónadas libres; como una ayuda para el aprendizaje, me las he arreglado para escribir una instancia Show
para el siguiente Free
Tipo:¿Puedo eliminar el uso de Incertidumbres Indecibles en esta instancia de Show para una Monad gratuita?
{-# LANGUAGE FlexibleContexts, UndecidableInstances #-}
-- Free monad datatype
data Free f a = Return a | Roll (f (Free f a))
instance Functor f => Monad (Free f) where
return = Return
Return a >>= f = f a
Roll ffa >>= f = Roll $ fmap (>>= f) ffa
-- Show instance for Free; requires FlexibleContexts and
-- UndecidableInstances
instance (Show (f (Free f a)), Show a) => Show (Free f a) where
show (Return x) = "Return (" ++ show x ++ ")"
show (Roll ffx) = "Roll (" ++ show ffx ++ ")"
-- Identity functor with Show instance
newtype Identity a = Id a deriving (Eq, Ord)
instance Show a => Show (Identity a) where
show (Id x) = "Id (" ++ show x ++ ")"
instance Functor (Identity) where
fmap f (Id x)= Id (f x)
-- Example computation in the Free monad
example1 :: Free Identity String
example1 = do x <- return "Hello"
y <- return "World"
return (x ++ " " ++ y)
El uso de UndecidableInstances
me molesta un poco; ¿Hay alguna manera de vivir sin eso? Todo lo que Google produce es this blog post by Edward Kmett, que reconfortantemente tiene básicamente la misma definición de clase Show
que yo.
'UndecidableInstances' no es realmente preocupante. Básicamente todo lo que hace es decirle al compilador "créeme, la persecución de instancias terminará". Si lo hiciste mal, la pila de contexto todavía impedirá que el compilador se quede atascado en un bucle infinito. –