0
data Nat = Zero | Succ Nat 
       deriving (Eq, Show)

-- Add two Natural number
addNat :: Nat -> Nat -> Nat 
addNat Zero Zero         = Zero
addNat Zero n@(Succ _)   = n
addNat n@(Succ _) Zero   = n
addNat (Succ x) (Succ y) = Succ (Succ (addNat x y))

I am confuse about the @ operator in Haskell function.

I am wondering what does addNat Zero n@(Succ _) = n means?

Does it mean that addNat Zero Succ b = Succ b?

wrek
  • 1,061
  • 5
  • 14
  • 26

1 Answers1

2

If name is a variable name, and pat is a pattern, then name@pat is a pattern that matches exactly when pat does, and also binds name to the value that matched pat. So:

addNat n@(Succ _) Zero = n

says "if the first argument is a Succ and the second is a Zero, then return the first argument".

Daniel Wagner
  • 145,880
  • 9
  • 220
  • 380
  • so, it is equivalent as `addNat (Succ n) Zero = Succ n`? – wrek May 07 '17 at 05:05
  • 1
    @wrek It is semantically equivalent, though GHC and other compilers may do something slightly different with that code. Specifically, with `addNat n@(Succ _) Zero = n`, GHC will not allocate a new `Nat`, whereas with `addNat (Succ n) Zero = Succ n`, GHC may (especially at low optimization levels) destruct the first argument and construct a *new* `Nat` with the same meaning as the old one. – Daniel Wagner May 07 '17 at 05:07