为什么功能组合需要括号?

时间:2016-08-11 20:40:43

标签: haskell syntax operator-precedence function-composition

假设我想用Text.pack撰写Text.strip

:t (.)生成:(b -> c) -> (a -> b) -> a -> c

:t (Text.pack)生成:String -> Text

:t (Text.strip)生成:Text -> Text

strip代替(b -> c)给出: b = Text c = Text

pack替换为(a -> b)给出: a = String b = Text

让我们验证::t strip . pack产生: strip . pack :: String -> Text

好吧,太棒了,试试吧:

strip.pack " example "

产地:

Couldn't match expected type ‘a -> Text’ with actual type ‘Text’
Relevant bindings include
  it :: a -> Text (bound at <interactive>:31:1)
Possible cause: ‘pack’ is applied to too many arguments
In the second argument of ‘(.)’, namely ‘pack "    example     "’
In the expression: strip . pack "    example     "

(strip . pack) " example "按预期工作....为什么?

2 个答案:

答案 0 :(得分:11)

功能应用程序的优先级高于组合。

strip.pack " example "相当于strip.(pack " example ")。这是人们在编写完所有函数之前使用$来“抑制”应用程序的一个原因:

strip . pack $ "    example     "

答案 1 :(得分:1)

函数应用程序的优先级高于函数组合运算符。