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 ?
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]is1:(2:(3:(4:[]))), in terms of its structure. So you want to matchfirstto1andlastto4, which are both subparts of the list, and thus not disqualified. But themiddlethat you want would be2:(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.