我正在学习 haskell,并且有点困惑函数应用运算符 $ curry 的用法。
根据 GHC,$ 的类型是
*Main>:t ($)
($) :: (a->b) -> a -> b
但我可以输入以下代码
*Main>map ($ 2) [(*2), (+2), (/2)]
[4.0,4.0,1.0]
根据 $ 的签名,尽管我假设我需要使用翻转函数,因为 $ 的第一个参数是 (a->b)。
例如,我无法执行以下操作
curry_test :: Integer -> String -> String
curry_test x y = (show x) ++ " " ++ y
*Main> let x = curry_test "123"
Couldn't match expected type `Integer' with actual type `[Char]'
In the first argument of `curry_test', namely `"123"'
In the expression: curry_test "123"
In an equation for `x': x = curry_test "123"
但我可以做
let x = curry_test 2
中缀运算符有特殊规则。请参阅此页面:http://www.haskell.org/haskellwiki/Section_of_an_infix_operator
基本上,自从$
是一个中缀运算符,($ 2)
实际上修复了2
作为第二个参数$
,所以它相当于flip ($) 2
.
这个想法是让运算符的部分应用程序更加直观,例如,如果您map (/ 2)
在列表上,您可以想象将列表中的每个元素放在除号左侧的“缺失”位置。
如果您想使用您的curry_test
以这种方式运行,你可以做
let x = (`curry_test` "123")
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)