我想减少以下锅炉板代码,但不使用镜头(Data.Label).我怎么能这样做呢?
data Qcfg = Qcfg { qthresh :: Int, tdelay :: Rational, cwpsq :: TPSQ, cwmap :: TMap, cwchan :: TChan String }
getQthresh = do
c <- ask
return (qthresh c)
getDelay = do
c <- ask
return (tdelay c)
getTMap = do
c <- ask
return (cwmap c)
getTPsq = do
c <- ask
return (cwpsq c)
getTChan = do
c <- ask
return (cwchan c)
Run Code Online (Sandbox Code Playgroud)
这些只是fmap的例子.这些都是等价的:
getQthresh = qthresh <$> ask
getQthresh'' = fmap qthresh ask
getQthresh''' = liftM qthresh ask
getQthresh' = do
c <- ask
return (qthresh c)
Run Code Online (Sandbox Code Playgroud)
该Data.Functor/ Control.Applicative版本<$>是你想要的; 如果你考虑一下,根本就没有样板.而你确实在为每个访问者浪费空间编写功能; 你只是一种新的方式来应用存取该fmap/<$>给你.如果你永远在写,<$> ask你可以定义
get field = field <$> ask
Run Code Online (Sandbox Code Playgroud)
也许这就是你现在所想的,我想起来了.然后
get qthresh
Run Code Online (Sandbox Code Playgroud)
会和你的一样
getQthresh
Run Code Online (Sandbox Code Playgroud)
和其他领域类似.当然你可以get用你的monadic方式定义这个(注意State有不同的一个):
get field = do
c <- ask
return (field c)
Run Code Online (Sandbox Code Playgroud)
对于具体案件的Reader存在asks f是fmap f ask,同样gets的State,但我走的问题是关于"解除"存取成仿函数或单子,因为它似乎它不是简单的说do {x <- action; return (f x)}就是f <$> action