gpt4 book ai didi

haskell - 类型注释的中缀优先级是什么 (::)

转载 作者:行者123 更新时间:2023-12-03 11:57:39 25 4
gpt4 key购买 nike

:: 的优先级是多少? ,有没有比它更低优先级的操作符?

似乎 :: 的优先级低于 $ , 因为下面的两个表达式都返回 "ab"

map head $ ["alice", "bob"] :: String
map head ["alice", "bob"] :: String

最佳答案

::部分称为类型注释。

邮件列表中的一条消息指向完全相同的结论,语法支持:

https://mail.haskell.org/pipermail/beginners/2012-December/011017.html

It's not really a binary operator.

It's part of the syntax, so it has no exact precedence, but since you're asking about it, I presume you're not interested in type declarations

foo :: Int -> Double  
foo = sin . fromIntegral

but rather in expression type signatures. The production in the context-free syntax is

exp → infixexp :: [context =>] type

so the signature is for the entire infix expression:

Prelude> toEnum . floor $ 12.7 + toEnum 73 :: Char
'U'

hence if it had a precedence, it would be below 0 (the precedence of ($)).

But be aware that

"The grammar is ambiguous regarding the extent of lambda abstractions, let expressions, and conditionals. The ambiguity is resolved by the meta-rule that each of these constructs extends as far to the right as possible."

thus

Prelude> (\x -> x + x :: Int -> Int) 2

<interactive>:16:10:
No instance for (Num (Int -> Int)) arising from a use of `+'
Possible fix: add an instance declaration for (Num (Int -> Int))
In the expression: x + x :: Int -> Int
In the expression: \ x -> x + x :: Int -> Int
In the expression: (\ x -> x + x :: Int -> Int) 2

the type signature here extends only over the x + x, since it is parsed as a part of the lambda abstraction

[ \x -> (x + x :: Int -> Int) extends farther to the right than just \x -> x + x ]

So if you want to give a type signature to a lambda abstraction, you need explicit parentheses:

Prelude> ((\x -> x + x) :: Int -> Int) 2 4

关于haskell - 类型注释的中缀优先级是什么 (::),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50961184/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com