避免重复使用字符串文字而不分配新变量

时间:2015-11-12 10:31:44

标签: haskell

我目前正在尝试通过清除针对GHCi选项-fwarn-incomplete-uni-patterns -Werror的一些代码来学习Haskell。

我试图清理的代码是:

infoM, warningM :: MonadIO m => String -> m ()
[infoM, warningM] = map ($ "Events.Reading") [L.infoM, L.warningM]

这导致模式匹配错误,因为匹配不是详尽无遗。

一个简单的解决方法是:

infoM, warningM :: MonadIO m => String -> m ()
infoM = L.infoM "Event.Reading"
warningM = L.warningM "Event.Reading"

然而,"Event.Reading"的双重使用似乎很混乱,使用let / inwhere组合可以轻松解决这个问题吗?

1 个答案:

答案 0 :(得分:3)

I'd go with a combinator

both :: (Arrow a) => a b c -> a (b, b) (c, c)
both f = f *** f

and then write it as

infoM, warningM :: MonadIO m => String -> m ()
(infoM, warningM) = both ($ "Events.Reading") (L.infoM, L.warningM)

Unfortunately, both is not in Control.Arrow last time I checked, but I think it should be added. For now, you can just write your own version.