有什么区别。 (点)和$(美元符号)? [英] What is the difference between . (dot) and $ (dollar sign)?

查看:182
本文介绍了有什么区别。 (点)和$(美元符号)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(。)和美元符号($)?之间有什么区别?据我了解,它们都是不需要使用圆括号的语法糖。

$ $ 运算符用于避免括号。例如,假设您有一行代码:

  putStrLn(show(1 + 1))


$ b $如果你想摆脱这些括号,下面任何一行也会做同样的事情:

  putStrLn(show $ 1 + 1)
putStrLn $ show(1 + 1)
putStrLn $ show $ 1 + 1

运算符的主要目的不是为了避免括号,而是为了链接函数。它可以让您将出现在右侧的任何输出与左侧出现的任何输入相关联。这通常也会减少括号,但工作方式不同。



回到相同的例子:

  putStrLn(show(1 + 1))




  1. (1 + 1)没有输入,因此不能用于运算符。
  2. show 可以带一个 Int 并返回一个 String

  3. 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 + 1) doesn't have an input, and therefore cannot be used with the . operator.
  2. show can take an Int and return a String.
  3. putStrLn can take a String and return an IO ().

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屋!

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