Pattern Matching

Previous Topic Next Topic
 
classic Classic list List threaded Threaded
2 messages Options
Reply | Threaded
Open this post in threaded view
|

Pattern Matching

Yugesh Kothari
This is probably a stupid question but I can't seem to understand the use of @ in haskell pattern matching.

Ex -
compress (x:ys@(y:_))
| x==y = compress us
| otherwise = x : compress us
compress us = us

Thanks!


_______________________________________________
Beginners mailing list
[hidden email]
http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners
Reply | Threaded
Open this post in threaded view
|

Re: Pattern Matching

Bob Ippolito
That’s called an as-pattern. It binds part of the pattern match to a variable. In this case you might want to do that for efficiency reasons. 

You can find an example of them here:

I think your example isn’t correct, the `us` variable is only defined for the last clause. The first two should use `compress ys`. 

Without as-patterns this would look like:

compress (x:y:ys’)
| x==y = compress (y:ys’)
| otherwise = x : compress (y:ys’)
compress us = us

It can be more efficient and concise to use ys@(y:_) in the pattern match and ys elsewhere  instead of having to repeat (y:ys’) which without optimizations would call the : constructor again and may not share memory in the same way. 

-bob


On Sat, Apr 27, 2019 at 07:31 Yugesh Kothari <[hidden email]> wrote:
This is probably a stupid question but I can't seem to understand the use of @ in haskell pattern matching.

Ex -
compress (x:ys@(y:_))
| x==y = compress us
| otherwise = x : compress us
compress us = us

Thanks!

_______________________________________________
Beginners mailing list
[hidden email]
http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners

_______________________________________________
Beginners mailing list
[hidden email]
http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners