Reputation: 125
I don't understand, how this function negative numbers catchs?
mdrop 0 [] = []
mdrop 0 (h:t) = h:t
mdrop n [] = []
mdrop n (h:t) = mdrop (n-1) t
If my input looks like this mdrop (-3) [1, 2, 3, 4, 5, 7, 88, 6]
I receive an empty list. But I don't understand in which line catches the negative number.
Upvotes: 2
Views: 1277
Reputation: 531490
Nothing catches the negative number specifically, but decreasing n
is always accompanied by a shorter list, so eventually you hit the empty list and the 3rd equation matches. n
is an example of an irrefutable pattern; it will match any number (positive, zero, or negative), although with the given definition, it will never be checked until you've already confirmed that the first argument is non-zero.
Effectively, a negative argument produces the same result as a sufficiently large argument, in that it can always be decremented without reaching 0.
Tracing it manually,
mdrop (-3) [1,2,3,4,5,7,88,6]
== mdrop (-4) [2,3,4,5,7,88,6]
== mdrop (-5) [3,4,5,7,88,6]
== mdrop (-6) [4,5,7,88,6]
== mdrop (-7) [5,7,88,6]
== mdrop (-8) [7,88,6]
== mdrop (-9) [88,6]
== mdrop (-10) [6]
== mdrop (-11) []
== []
As an aside, your first two definitions could be replaced by the single definition
mdrop 0 xs = xs
since in both original definitions, you simply return the second argument when you the first matches 0.
Upvotes: 7