Understanding the Haskell as-pattern

空扰寡人 提交于 2019-12-08 08:49:01

问题


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.


回答1:


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.




回答2:


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').



来源:https://stackoverflow.com/questions/27467650/understanding-the-haskell-as-pattern

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!