What does (n+1) mean? I understand both are recursive Haskell functions and are using pattern matching.
I don't understand how it will pattern match factorial (n+1) as well as the (n+1) on the RHS of factorial =.
And with the drop function why is it drop 0 xs = xs? And what about drop (n+1) [] = []?
--Example 1
factorial 0 = 1
factorial (n+1) = (n+1) * factorial n
--Example 2
drop :: Int -> [a] -> [a]
drop 0 xs = xs
drop (n+1) [] = []
drop (n+1) (_:xs) = drop n xs
By the way I get errors when compiling.
Update: Thanks for pointing me to the correct terminology. I found this n+k patterns. Since n+k patterns have been removed since 2010 I also found this question on how to enable this pattern.
These are NPlusKPatterns, which were removed from the language in 2010, and are now only available with the mentioned language extension.
An n + k-pattern
drop (n+1) [] = []
binds n to the argument value minus one, provided that the argument value is >= 1. The pattern does not match arguments <= 0.
So if
drop :: Int -> [a] -> [a]
drop 0 xs = xs
drop (n+1) [] = []
drop (n+1) (_:xs) = drop n xs
is called with a negative Int argument, like
drop (-2) "foo"
no pattern matches, and you get an exception.
Generally, if you define (for a stupid example)
foo :: Int -> Int
foo (n+5) = 3*n
foo (n+2) = n
foo (n+1) = 2*n
if you call foo 7, the first pattern matches and n will be bound to 2, so foo 7 = 6. If you call foo 3, the first pattern doesn't match (3-5 = -2 < 0), but the second does, and that binds n to 3-2 = 1, hence foo 3 = 1. If you call foo 1, neither of the first two patterns matches, but the last does, and then n is bound to 1 - 1 = 0, so foo 1 = 0. Calling foo with an argument < 1 raises an exception.
And with drop function why is it
drop 0 xs = xs? And what aboutdrop (n+1) [] = []?
Well, drop 0 drops 0 elements from the front of the list, so it doesn't change the list argument at all. And you can't drop elements from an empty list, so drop (n+1) [] = [] is the only thing you can do except raising an error.
This is a so called n+k pattern. The pattern (n+1) matches any positive integer and gives n the value of that integer minus one. So if you call drop 1 xs the value of n will be 0.
why is it
drop 0 xs = xs
Because if you remove 0 elements from a list, you end up with the same list.
And what about
drop (n+1) [] = []?
That says that if you remove any amount of items from the empty list, you end up with a list that's still empty. Other than failing with an error message, that's really the only sensible thing you can do in that case.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With