简体   繁体   中英

What does '@' mean in Haskell?

I've tried googling but come up short. I am furthering my Haskell knowledge by reading some articles and I came across one that uses a syntax I've never seen before. An example would be:

reconstruct node@(Node a b c l r) parent@(Node b d le ri)

I've never seen these @'s before. I tried searching online for an answer but came up short. Is this simply a way to embed tags to help make things clearer, or do they have an actual impact on the code?

It is used in pattern matching. Now node variable will refer to the entire Node data type for the argument Node abclr . So instead of passing to the function as Node abclr , you can use node instead to pass it up.

A much simpler example to demonstrate it:

data SomeType = Leaf Int Int Int | Nil deriving Show

someFunction :: SomeType -> SomeType
someFunction leaf@(Leaf _ _ _) = leaf
someFunction Nil = Leaf 0 0 0

The someFunction can also be written as:

someFunction :: SomeType -> SomeType
someFunction (Leaf x y z) = Leaf x y z
someFunction Nil = Leaf 0 0 0

See how simpler was the first version ?

Besides the argument pattern matching usage described in the answer of @Sibi, in Haskell the "at" character ('@', also known as an arobase character) can be used in some contexts to force a typing decision. This is mentioned in the comments by @Josh.F.

This is not part of the default language features, and is known as the Type Application Haskell language extension. In summary, the extension allows you to give explicit type arguments to a polymorphic function such as read . In a classic .hs source file, the relevant pragma must be included:

{-#  LANGUAGE TypeApplications  #-}

Example:

$ ghci
GHCi, version 8.2.2: http://www.haskell.org/ghc/  :? for help
 λ> 
 λ> let x = (read @Integer "33")

 <interactive>:4:10: error:
    Pattern syntax in expression context: read@Integer
    Did you mean to enable TypeApplications?
 λ> 
 λ> :set -XTypeApplications
 λ>
 λ> let x = (read @Integer "33")
 λ>
 λ> :t x
 x :: Integer
 λ> 
 λ> x
 33
 λ> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM