What is the precedence of `->`, `=` and ` ` in Haskell?

柔情痞子 提交于 2019-12-10 14:56:08

问题


I'm trying to figure out some default operator precedences in Haskell, but I was unable to find some good documentation on ->, = and (as in f x). So I tried :i (->) and :i (=) in GHCI to get some info, but it gives me a syntax error.

Apparently these "tokens" are just a built-in part of the syntax, so no wonder, that :i doesn't work.

I'm new to Haskell, so I wasn't aware of the fact, that = doesn't return any value, I just mistakingly assumed, that it behaves as its equivalents in imperative languages, which is wrong of course.

-> and , on the other hand, behave as operators. They return a type/value and are right/left associative respectively. And they have some sort of perecedence when used along with actual operators.


回答1:


  • -> is a type-level operator ((->) :: * -> * -> *), and as mentioned in comments, :i (->) reveals that it is infixr 0*.
  • Function application could be seen as having 'infinitely high' left precedence, that is to say if % is any operator, then f x % y will always be read as (f x) % y no matter what precedence % has, and f x y z is always read as ((f x) y) z.** This isn't documented as having a precedence, because it isn't an operator, and 'infinite' precedence can't be declared in Haskell.
  • = cannot be seen as having precendence, as it is always declaration rather than an expression, so putting parentheses around it is absurd. It is not an operator, hence cannot have precedence.

* As pointed out in a below comment, this actually behaves as if it has precedence infixr -1, but this is not permitted in ordinary operators — this is syntactic rather than semantic.

** Note that this is the 'opposite' of ->, which could be seen as having 'infinitely low', right precedence. Can you see why this is natural?



来源:https://stackoverflow.com/questions/56202894/what-is-the-precedence-of-and-in-haskell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!