Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell pattern matching the first, middle section, and last

So I wanted to do a simple string reverse function in Haskell

swapReverse :: String => String  
swapReverse [x] = [x]
swapReverse [x,y] = [y,x]
swapReverse (x:xs:l) =         -- pattern match fails here 
  let last = [l]
      middle = xs
      first = [x]
  in  last ++ swapReverse middle ++ first

So is there a way to define a pattern structure in haskell that has first and last element, and all the elements in the middle ?

like image 789
nobody Avatar asked Mar 21 '12 21:03

nobody


1 Answers

No, you cannot. Why? Because pattern matches match values and their subparts, but the "middle" of a list isn't a subpart of the list. The list [1, 2, 3, 4] is 1:(2:(3:(4:[]))), in terms of its structure. So you want to match first to 1 and last to 4, which are both subparts of the list, and thus not disqualified. But the middle that you want would be 2:(3:[]), which is not a subpart of the list, and thus, cannot be a match.

Note that we can't write a pattern to match the first and the last elements of a list simultaneously, either. A pattern has a depth that's fixed at compilation time.

like image 113
Luis Casillas Avatar answered Oct 10 '22 10:10

Luis Casillas