(x:xs) pattern Haskell logic

扶醉桌前 提交于 2019-12-12 02:56:57

问题


Let's say there is a simple function:

maximum' :: (Ord a) => [a] -> a  
maximum' [] = error "maximum of empty list"  
maximum' [x] = x  
maximum' (x:xs) = max x (maximum' xs)

I understand the idea and what (x:xs) does. As it was explained in details here What do the parentheses signify in (x:xs) when pattern matching? but there is one little thing that I cannot get out of my head. Since cons: operator appends x to a list xs, why is it that x is the first element of function argument list and xs is the tail when we use (x:xs)??? as if (x:xs) calls head and tail on argument list.


回答1:


This is just an instance of the general pattern that the constructor for a type is both used to construct elements of that type and to deconstruct. If you wrote

data MyList a = Empty | Cons a (MyList a)

you'd write

maximum' :: (Ord a) => MyList a -> a  
maximum' Empty = error "maximum of empty list"  
maximum' (Cons x Empty) = x  
maximum' (Cons x xs) = max x (maximum' xs)

Except that lists are actually defined equivalently to

data [a] = [] | a:as

so, just as with other data types, : is used both to construct and to deconstruct nonempty lists.




回答2:


The cons operator doesn't append, it prepends. That is x : xs produces a list that contains x as its first element and xs as the rest. Therefore the pattern x : xs likewise matches a list with x as the first element and xs as the rest.



来源:https://stackoverflow.com/questions/35278382/xxs-pattern-haskell-logic

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