TE
科技回声
首页24小时热榜最新最佳问答展示工作
GitHubTwitter
首页

科技回声

基于 Next.js 构建的科技新闻平台,提供全球科技新闻和讨论内容。

GitHubTwitter

首页

首页最新最佳问答展示工作

资源链接

HackerNews API原版 HackerNewsNext.js

© 2025 科技回声. 版权所有。

Unit testing IO in Haskell

69 点作者 fractalsea超过 9 年前

3 条评论

gamegoblin超过 9 年前
This is a good post in that it illustrates how it&#x27;s possible to write useful Haskell that interacts with the real world without weaving IO through the entire codebase (as many beginners end up doing).<p>I still find myself preferring to use a dependency injection style when writing Haskell. The code ends up looking similar, and more flexible, in my opinion (you can inject different dependencies based on runtime values).<p>Here is an example using the method described in the article vs. dependency injection to print out the current time.<p>Article:<p><pre><code> class MonadTime m where getTime :: m Integer class MonadPrint m a where doPrint :: a -&gt; m () instance MonadTime IO where getTime = do TOD s _ &lt;- getClockTime return s instance Show a =&gt; MonadPrint IO a where doPrint = print printTime :: (Monad m, MonadPrint m Integer, MonadTime m) =&gt; m () printTime = getTime &gt;&gt;= doPrint main :: IO () main = printTime </code></pre> Dependency injected:<p><pre><code> data MonadPrint m a = MonadPrint { doPrint :: a -&gt; m () } data MonadTime m = MonadTime { getTime :: m Integer } ioMonadTime :: IO Integer ioMonadTime = do TOD s _ &lt;- getClockTime return s printTime :: Monad m =&gt; MonadPrint m Integer -&gt; MonadTime m -&gt; m () printTime MonadPrint{..} MonadTime{..} = getTime &gt;&gt;= doPrint main :: IO () main = printTime (MonadPrint print) (MonadTime ioMonadTime) </code></pre> Good read on the subject of being careful with overusing typeclasses:<p><a href="http:&#x2F;&#x2F;www.haskellforall.com&#x2F;2012&#x2F;05&#x2F;scrap-your-type-classes.html" rel="nofollow">http:&#x2F;&#x2F;www.haskellforall.com&#x2F;2012&#x2F;05&#x2F;scrap-your-type-classes...</a>
评论 #10396511 未加载
LukeHoersten超过 9 年前
Pusher is doing some awesome stuff with Haskell! They run a lot of the bitcoin exchange web socket APIs on their infrastructure. I&#x27;m sure they have other users too. Cool stuff.
bartq超过 9 年前
finally someone did haskell examples in decent modern blog UI instead of old fashioned dark depressing terminal-like colors ;)
评论 #10396587 未加载