[Haskell-cafe] Re: what does @ mean?.....

ChrisK haskell at list.mightyreason.com
Fri Dec 28 06:31:50 EST 2007


Nicholls, Mark wrote:
> Hello, I wonder if someone could answer the following…
> 
> The short question is what does @ mean in
> 
>  
> 
> mulNat a b
> 
>     | a <= b = mulNat' a b b
> 
>     | otherwise = mulNat' b a a
> 
>     where
> 
>          mulNat' x@(S a) y orig
> 
>                  | x == one = y
> 
>                  | otherwise = mulNat' a (addNat orig y) orig
> 

The @ means an as-pattern as defined in the Haskell 98 report section 3.17.1
http://www.haskell.org/onlinereport/exps.html#3.17.1

The 'x' binds to the whole (S a) and the 'a' binds to the parameter of the
constructor 's'.

There is a possible performance benefit here.  Consider:

zeroNothing Nothing = Nothing
zeroNothing (Just n) =
  if n == 0 then Nothing else (Just n)

versus

zeroNothing Nothing = Nothing
zeroNothing x@(Just n) =
  if n == 0 then Nothing else x


The first example takes apart the (Just n) and later reconstructs (Just n).
Unless the compiler is fairly clever, this will cause the new (Just n) to be a
new allocation instead of reusing the input value.  The second form uses an
at-pattern to bind 'x' to the whole input parameter and the returned 'x' will
not need to be reallocaed.

-- 
Chris



More information about the Haskell-Cafe mailing list