$和()之间的区别 [英] Difference between $ and ()
问题描述
让findKey key xs = snd。头。过滤器(\(k,v) - > key == k)$ xs
摆弄一下,决定用这种方式摆脱$ sign:
让findKey key xs = snd。头。过滤器(\(k,v) - > key == k)(xs)
,它甚至不解析(过滤器应用于太多的argumens错误)。我已经读过$ sign用来简单地替换括号,我无法弄清楚为什么简单的代码改变是不好的。有人可以解释给我吗?
中缀运算符($)
就是功能应用程序。换句话说,
fx - 和
f $ x
(f。g。i。j)x
有时更好阅读。
有时候我们想要能够传递函数应用的想法。例如,如果我们有一个函数列表
lof :: [Int - > Int]
lof = [(+1),(减1),(* 2)]
我们可能希望通过一个值来映射应用程序,例如将数字 4
应用于每个函数
> map(\fun-> fun 4)lof
[5,3,8]
<但是由于这只是函数应用程序,所以我们也可以使用
> map $ 4 $
[5,3,8]
I started learning Haskell and I encountered a problem I can't just understand. I've got a method used to find value from a list of key-value list (from this page):
let findKey key xs = snd . head . filter (\(k,v) -> key == k) $ xs
I tried fiddling with a bit and decided to get rid of $ sign in this way:
let findKey key xs = snd . head . filter (\(k,v) -> key == k) ( xs )
However, it doesn't even parse (filter applied to too many argumens error). I've read that $ sign is used to simply replace parenthesis and I can't figure out why this simple change of code is bad. Could someone explain it to me?
The infix operator ($)
is just "function application". In other words
f x -- and
f $ x
are the same. Since in Haskell parentheses are only used to disambiguate precedence (and for tuple notation and a few other minor places, see comments) we can also write the above in a few other ways
f x
f $ x
(f) x
f (x)
(f) (x) -- and even
(f) $ (x)
In every case, the above expressions denote the same thing: "apply the function f
to the argument x
".
So why have all this syntax? ($)
is useful for two reasons
- It has really low precedence so it can stand in for a lot of parentheses sometimes
- It's nice to have an explicit name for the action of function application
In the first case, consider the following deeply right-nested function application
f (g (h (i (j x))))
It can be a little difficult to read this and a little difficult to know you have the right number of parentheses. However, it's "just" a bunch of applications so there ought to be a representation of this phrase using ($)
. Indeed there is
f $ g $ h $ i $ j $ x
Some people find this easier to read. More modern style also incorporates (.)
in order to emphasize that the whole left side of this phrase is just a composed pipeline of functions
f . g . h . i . j $ x
And this phrase is, as we saw above, identical to
(f . g . h . i . j) x
which is sometimes nicer to read.
There are also times when we want to be able to pass around the idea of function application. For instance, if we have a list of functions
lof :: [Int -> Int]
lof = [ (+1), (subtract 1), (*2) ]
we might want to map application by a value over them, for instance apply the number 4
to each function
> map (\fun -> fun 4) lof
[ 5, 3, 8 ]
But since this is just function application, we can also use section syntax over ($)
to be a bit more explicit
> map ($ 4) lof
[ 5, 3, 8 ]
这篇关于$和()之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!