Alex Rivera | Logout

Haskell pattern matching the first, middle section, and last

Asked 2012-03-21T21:10:17.583
8

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 ?

Edit
Report

3 Answers

5

Pattern matching works on constructors, : is the only list constructor so you can not match on the middle of the list. You need to construct the new list backwards (obviously :) ) which can be done by taking the head and appending that to the reverse of the rest of the list.

answered 2012-03-21T21:31:13.497
2

Try this code:

last1 (x:xs:l) = (x,xs,l)

l doesn't get you the last element in a list, it get's you the rest of the list besides the first two variables, which are assigned the first two elements in a list.

When you write a pattern match for a list, the first variable is assigned the first element, and so on, until the program get's to the last variable, where everything that is left is assigned to it. There is nothing special about adding an s after an x, a variable named y would do the same thing.

If you want to get the last element of a list, you need to create a pattern similar to (x:xs), and use recursion on xs and apply that pattern until you get down to one list element, which is the last element. However, I would recommend reading Adam Bergmark's answer for a better way to reverse a list that does not involve finding the first and last elements of a list.

answered 2012-03-21T22:23:20.603
0

A working version:

swapReverse :: String -> String  
swapReverse (x:xs) = [last xs] ++ swapReverse (init xs) ++ [x]
swapReverse xs = xs

Note that this implementation is performance-wise a disaster. Implementations using a fold and/or accumulators are much more efficient.

answered 2012-03-22T09:52:29.467

Your Answer