Mic*_*ron 3 haskell functional-programming function where
我有一个正在增长的功能,它正在获得如下所示的模式.什么是这些的适当替代品,其中f = fooed e等于裸露e等于bazed d ...?
myFunc:: String -> Options -> String
myFunc someString opts = topStr ++ editedMidStr ++ botStr
where editedMidStr = foo f
f = bar e
e = baz d
d = qux c
... = ...
Run Code Online (Sandbox Code Playgroud)
最明显的方法是简单地将每个论点都放在parens中:
where editedMidStr = foo (bar (baz ... (qux x)...))
Run Code Online (Sandbox Code Playgroud)
然而,这很丑陋,很难看出什么是匹配的.在Haskell中通常首选避免使用parens(如果可能的话)支持"括号运算符"
Prelude>:i $
($)::(a - > b) - > a - > b - 在'
GHC.Base'infixr 0 $中定义
这是真的就像一个缀+或者==,只是它不会做任何事情,但保持参数两侧分开.LHS是应用于RHS的功能.所以,你可以写bar (baz q)的bar $ baz q.因为它$是右关联的,你可以添加更多功能:
foo (bar (baz q)) ? foo $ bar $ baz q
Run Code Online (Sandbox Code Playgroud)
这是非常简洁的,但它仍然可以被重写为更优雅的东西.这种非常常见的即时结果到另一种功能范例称为功能组合.
foo (bar (baz q)) ? (foo . bar . baz) q
Run Code Online (Sandbox Code Playgroud)
为什么我们更喜欢这个?首先,它更具有重构友好性.如果管道变得太长,你可以取出任何一块并给它一个有意义的名字.
最好的形式IMO是使用组合和$:
foo . bar . baz $ q
Run Code Online (Sandbox Code Playgroud)
要么
foo . bar $ baz q
Run Code Online (Sandbox Code Playgroud)
使用功能组合!
myFunc myString opts = topStr ++ editedMidStr ++ botStr where
editedMidStr = (foo . bar . baz . qux . makeACFromMyString) myString
Run Code Online (Sandbox Code Playgroud)