3

I'm reading through Real World Haskell, and am trying to understand the as-pattern.

From the book (Chapter 4):

suffixes :: [a] -> [[a]]
suffixes xs@(_:xs') = xs : suffixes xs'
suffixes _ = []

The book explains the @ symbol thus,

"...bind the variable xs to the value that matches the right side of the @ symbol."

I'm having trouble understanding this explanation. Supposing I call

suffixes "hello"

Explicitly, what would the above line with the @ do to this (on the first iteration)? I know what the result of the function is, but cannot see how we get there from the above code.

duplode
  • 33,731
  • 7
  • 79
  • 150
  • possible duplicate of [What does the "@" symbol mean in reference to lists in Haskell?](http://stackoverflow.com/questions/1153465/what-does-the-symbol-mean-in-reference-to-lists-in-haskell) – duplode Aug 14 '15 at 00:14

2 Answers2

16

xs' would be bound to the string "ello".

xs would be bound to the string "hello".

The @ pattern lets you give a name to a variable while also matching its structure and possibly giving name to the components.

Ptival
  • 9,167
  • 36
  • 53
9

Perhaps an actual "de-sugaring" will make it easier to understand:

suffixes xs@(_:xs') = xs : suffixes xs'

is equivalent to

suffixes xs
 | (_:xs') <- xs   = xs : suffixes xs'

i.e. you're firstly binding the entire argument to the variable xs, but you also do pattern matching on the same argument (or, equivalently, on xs) to (_:xs').

leftaroundabout
  • 117,950
  • 5
  • 174
  • 319