有什么区别。 (点)和$(美元符号)? [英] What is the difference between . (dot) and $ (dollar sign)?
问题描述
点(。)
和美元符号($)
?之间有什么区别?据我了解,它们都是不需要使用圆括号的语法糖。
$ $
运算符用于避免括号。例如,假设您有一行代码: putStrLn(show(1 + 1))
$ b $如果你想摆脱这些括号,下面任何一行也会做同样的事情:
putStrLn(show $ 1 + 1)
putStrLn $ show(1 + 1)
putStrLn $ show $ 1 + 1
。
运算符的主要目的不是为了避免括号,而是为了链接函数。它可以让您将出现在右侧的任何输出与左侧出现的任何输入相关联。这通常也会减少括号,但工作方式不同。
回到相同的例子:
putStrLn(show(1 + 1))
-
(1 + 1)
没有输入,因此不能用于。
运算符。
-
show
可以带一个Int
并返回一个String
。 -
putStrLn
可以带一个String
返回一个IO()
。
code> show to putStrLn
就像这样:
(putStrLn。show)(1 + 1)
如果括号太多你喜欢用 $
运算符去除它们:
putStrLn 。显示$ 1 + 1
What is the difference between the dot (.)
and the dollar sign ($)
?. As I understand it, they are both syntactic sugar for not needing to use parentheses.
The $
operator is for avoiding parentheses. Anything appearing after it will take precedence over anything that comes before.
For example, let's say you've got a line that reads:
putStrLn (show (1 + 1))
If you want to get rid of those parentheses, any of the following lines would also do the same thing:
putStrLn (show $ 1 + 1)
putStrLn $ show (1 + 1)
putStrLn $ show $ 1 + 1
The primary purpose of the .
operator is not to avoid parentheses, but to chain functions. It lets you tie the output of whatever appears on the right to the input of whatever appears on the left. This usually also results in fewer parentheses, but works differently.
Going back to the same example:
putStrLn (show (1 + 1))
(1 + 1)
doesn't have an input, and therefore cannot be used with the.
operator.show
can take anInt
and return aString
.putStrLn
can take aString
and return anIO ()
.
You can chain show
to putStrLn
like this:
(putStrLn . show) (1 + 1)
If that's too many parentheses for your liking, get rid of them with the $
operator:
putStrLn . show $ 1 + 1
这篇关于有什么区别。 (点)和$(美元符号)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!