如何使用$运算符对Haskell进行函数应用? [英] How does function application with the $ operator curry in Haskell?

查看:127
本文介绍了如何使用$运算符对Haskell进行函数应用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



根据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 
curry_test x y =(show x)++++ y
* Main> let x = curry_test123
无法与实际类型为'[Char]'的$ Integer相匹配'
'在`curry_test'的第一个参数中,即`123'
在表达式中:curry_test123
在'x'的等式中:x = curry_test123

但我可以做
$ b $ pre $ let x = curry_test 2

解决方案

Infix操作符有特殊的规则。见本页: http://www.haskell.org/haskellwiki/Section_of_an_infix_operator



基本上,因为 $ 是一个中缀运算符,所以($ 2)实际上修正了 2 作为 $ 的第二个参数,所以它相当于 flip($)2

这个想法是让运算符的部分应用程序更加直观,例如,如果 map(/ 2)在列表中,您可以想象将列表中的每个元素放置在划分符号左侧的缺失位置。



如果要使用 curry_test 函数用这种方法,你可以做

$ p code> let x =(`curry_test `123)


I am learning haskell and am a little confused how the function application operator $ curry's.

According to GHC the type of $ is

*Main>:t ($)
($) :: (a->b) -> a -> b

But I can type the following code

*Main>map ($ 2) [(*2), (+2), (/2)]
[4.0,4.0,1.0]

According to the signature of $ though I would assume I would need to use the flip function because the first parameter to $ is (a->b).

For example, I can't do the following

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"

But I can do

let x = curry_test 2

解决方案

Infix operators have special rules. See this page: http://www.haskell.org/haskellwiki/Section_of_an_infix_operator

Basically, since $ is an infix operator, ($ 2) actually fixes 2 as the second argument of $, so it is equivalent to flip ($) 2.

The idea is to make partial application with operators more intuitive, so for example if you map (/ 2) over a list, you can imagine putting each element of the list in the "missing" spot on the left side of the division sign.

If you want to use your curry_test function this way, you could do

let x = (`curry_test` "123")

这篇关于如何使用$运算符对Haskell进行函数应用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆