I was doing the 99 Problems in Haskell when I encountered a solution to Problem 19 that I did not fully understand.

The task is to write a rotate function that works like this

*Main> rotate ['a','b','c','d','e','f','g','h'] 3
"defghabc"

*Main> rotate ['a','b','c','d','e','f','g','h'] (-2)
"ghabcdef"

One provided solution is

rotate [] _ = []
rotate l 0 = l
rotate (x:xs) (n+1) = rotate (xs ++ [x]) n
rotate l n = rotate l (length l + n)

I don't understand how the pattern matching can ever reach the fourth line. It seems to have to do with the (n+1) so that when n is negative the third line does not match and therefore the fourth is taken. If that is the case why does the notation (n+1) work that way resp. isn't that arbitrary or is that a convention (in mathematics?) that I'm not aware of?

Because the way I understand it is that rotate is called recursively in the third line with the argument n reduced by one. So I would think that

rotate [] _ = []
rotate l 0 = l
rotate (x:xs) n = rotate (xs ++ [x]) (n-1)
rotate l n = rotate l (length l + n)

is equivalent. However, it is not. This definition gives the following warning

Warning: Pattern match(es) are overlapped
         In the definition of `rotate': rotate l n = ...

whereas the former definition compiles just fine.

Edit
Report