मैं अपने मुफ़्त मोनादों के चारों ओर अपने सिर को लपेटने की कोशिश कर रहा हूं; एक सीखने सहायता के रूप में, मैं निम्नलिखित Free
प्रकार के लिए एक Show
उदाहरण लिखने के लिए प्रबंधित किया है:क्या मैं एक मुक्त मोनाड के लिए इस शो इंस्टेंस में UndecidableInstances के उपयोग को समाप्त कर सकता हूं?
{-# 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)
UndecidableInstances
के उपयोग मुझे परेशान कुछ हद तक; क्या इसके बिना करने का कोई तरीका है? Google की सभी कमाई this blog post by Edward Kmett है, जो मूल रूप से वही Show
क्लास परिभाषा है जो मैं करता हूं।
'अपरिहार्य इंस्टेंस' वास्तव में चिंताजनक नहीं है। असल में यह सब करता है संकलक 'मुझे विश्वास करो, उदाहरण पीछा समाप्त हो जाएगा'। यदि आपको यह गलत लगता है, तो संदर्भ स्टैक अभी भी कंपाइलर को अनंत लूप में फंसने से रोक देगा। –