Haskell中如何将多个单子操作应用于同一参数并简化重复代码?
简化Haskell代码消除重复参数的方法
当然有办法,下面几种方式都能消除"hello world"的重复,同时把三个单子操作应用到同一参数上:
方法1:用let绑定复用参数
这是最直观的方式,先把重复的字符串存到变量里,后续直接引用:
fn = do let msg = "hello world" a <- f msg b <- g msg c <- h msg return (a, b, c)
方法2:利用Applicative组合子
因为你的三个单子操作彼此独立(不需要依赖前一个操作的结果),用Applicative风格会更简洁。可以用<$>和<*>组合,或者用liftA3:
方式2.1:手动Applicative组合
fn = (,,) <$> f "hello world" <*> g "hello world" <*> h "hello world"
方式2.2:使用liftA3
需要先导入Control.Applicative模块:
import Control.Applicative (liftA3) fn = liftA3 (,,) (f "hello world") (g "hello world") (h "hello world")
方法3:结合let绑定和Applicative
如果想同时消除参数重复和简化do notation,可以把两者结合:
fn = let msg = "hello world" in (,,) <$> f msg <*> g msg <*> h msg
补充说明:当多个单子操作之间没有依赖关系时,Applicative风格比do notation更贴合函数式编程的简洁性原则,do notation更多适用于有依赖的序列操作。
内容的提问来源于stack exchange,提问作者Niek
相关产品推荐
相关产品推荐

