1
關於Control.Applicative,如果我有以下表現:Control.Applicative優先
f = (expr1 <|> expr2) <* expr3
是必要的括號?也就是說,不管採取哪個分支,expr3
都會被評估(並拋棄)?
關於Control.Applicative,如果我有以下表現:Control.Applicative優先
f = (expr1 <|> expr2) <* expr3
是必要的括號?也就是說,不管採取哪個分支,expr3
都會被評估(並拋棄)?
你可以要求ghci
爲優先權信息:
Prelude Control.Applicative> :i <|>
class Applicative f => Alternative f where
...
(<|>) :: f a -> f a -> f a
...
-- Defined in `Control.Applicative'
infixl 3 <|>
Prelude Control.Applicative> :i <*
class Functor f => Applicative f where
...
(<*) :: f a -> f b -> f a
-- Defined in `Control.Applicative'
infixl 4 <*
中的相關位有以下兩行:
infixl 3 <|>
infixl 4 <*
由於<*
具有更高的優先級(4),其結合更緊密;所以是的,括號是需要的,以防止被解析爲expr1 <|> (expr2 <* expr3)
。
<|>
優先級爲3; <*
of 4.所以括號是必需的。
$ ghci
λ import Control.Applicative
λ :info <|>
class Applicative f => Alternative f where
...
(<|>) :: f a -> f a -> f a
...
-- Defined in `Control.Applicative'
infixl 3 <|>
λ :info <*
class Functor f => Applicative f where
...
(<*) :: f a -> f b -> f a
-- Defined in `Control.Applicative'
infixl 4 <*
謝謝。這是我的直覺,但我不確定。 –