[Haskell-beginners] Pattern Matching
Bob Ippolito
bob at redivi.com
Sat Apr 27 15:24:07 UTC 2019
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:
https://www.haskell.org/tutorial/patterns.html
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 <kothariyugesh at gmail.com>
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
> Beginners at haskell.org
> http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.haskell.org/pipermail/beginners/attachments/20190427/ebc71c3d/attachment.html>
More information about the Beginners
mailing list