I know what the following function does I would just like an explanation of how it works and the calculations that take place:
sponge :: Int -> [a] -> [a]
sponge 0 xs = xs
sponge n [] = []
sponge n (x:xs) = sponge (n-1) xs
I just seem to have lost the plot with it all now 🙁
Any help to get me back on track would be much appreciated! 🙂
It’s a recursive function over two variables. You can break it apart line-by-line to understand it:
Two arguments, one an
Int, one a list of some elements.The base case. If the
Intargument is zero, just return the list argument unmodified.Another base case, if the list is empty, immediately return the empty list.
Finally, the inductive step. If the list is non-empty (i.e. made up of at least one element and a tail, denoted by
x:xs), then the result isspongecalled onn-1and the tail of the list.So what will this function do? It will return the tail of the list after dropping
nelements. It is the same as thedropfunction:And
In fact, we can ask QuickCheck to confirm:
Ah! They’re different. When
nis negative! So we can modify the property relating the two functions:So your function behaves like drop, for cases when
nis positive.Here’s a trace of the intermediate values of
nandxs, obtained via the hood debugger: