I'm 尝试不同的方法执行有时称为依赖项注入的操作。为此,我详细阐述了一个天气应用程序的简单示例,我们要在其中获取天气数据(从网络服务或硬件设备),存储天气数据(可以是数据库或简单的文件),并报告(将其打印到屏幕上,或说出天气)。这个想法是编写一个程序,使用一些fetch
, store
, and report
函数,其实现可能会有所不同。
我已经成功地将关注点从检索、存储和报告的实现中分离出来,并使用功能 and 自由单子,但是我用 monad stacks 达成的解决方案看起来很糟糕:
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module WeatherReporterMTL where
import Control.Monad.IO.Class
import Control.Monad.Trans.Class
type WeatherData = String
class Monad m => WeatherService m where
fetch :: m WeatherData
class Monad m => Storage m where
store :: WeatherData -> m ()
class Monad m => Reporter m where
report :: WeatherData -> m ()
-- | A dummy implementation of the @WeatherService@
newtype DummyService m a = DummyService { runDummyService :: m a }
deriving (Functor, Applicative, Monad, MonadIO)
instance MonadIO m => WeatherService (DummyService m) where
fetch = return "won't get any warmer in December."
-- | A dummy implementation of the @Storage@
newtype DummyStorage m a = DummyStorage { runDummyStorage :: m a }
deriving (Functor, Applicative, Monad, MonadIO, WeatherService)
-- It seems wrong that the storage has to be an instance the weather service
-- (@WeatherService@) ...
instance MonadIO m => Storage (DummyStorage m) where
store d = liftIO $ putStrLn $ "No room left for this report: " ++ d
-- | A dummy implementation of the @Reporter@
newtype DummyReporter m a = DummyReporter { runDummyReporter :: m a }
deriving (Functor, Applicative, Monad, MonadIO, WeatherService, Storage)
-- Ok, now this seems even worse: we're putting information about
-- how we're gonna stack our monads :/
instance MonadIO m => Reporter (DummyReporter m) where
report d = liftIO $ putStrLn $ "Here at the MTL side " ++ d
reportWeather :: (WeatherService m, Storage m, Reporter m) => m ()
reportWeather = do
w <- fetch
store w
report w
dummyWeatherReport :: IO ()
dummyWeatherReport = runDummyService $ runDummyStorage $ runDummyReporter reportWeather
在上面的代码中,两者DummyStorage
and DummyReporter
必须有简单的实例WeatherService
,这显然是错误的。此外,这些实例取决于单子最终堆叠的顺序。有没有办法避免不同堆栈之间的信息泄漏?