So, there is something known as a "universal property of fold", stating exactly following:
g [] = i; g (x:xs) = f x (g xs)
<=> g = fold f i
However, as you probably now, there are rare cases like dropWhile
, which can not be redefined as fold f i
unless you generalize it.
The simplest yet obvious way to generalize is to redefine universal property:
g' y [] = j y; g' y (x:xs) = h y x xs (g' y xs)
<=> g' y = fold (?) l
At this point I can make my assumption: I assume existence of somewhat function p :: a -> b -> b
, which would satisfy the equation g' y = fold p l
. Let's try to solve given equation with help of universal property, mention at the very beginning:
g' y [] = j y = fold p l [] = l
=>j y = l
g' y (x:xs) = h y x xs (g' y xs) = fold p l (x:xs) = p x (fold p l xs) = p x (g' y xs)
=> lettingrs = (g' y xs)
,h y x xs rs = p x rs
, which is wrong:xs
occurs freely from the left and thus equality can't hold.
Now let me try to interpret result I've came up with and ask question.
I see that the problem is xs
emerging as unbound variable; it's true for various situations, including above mentioned dropWhile
. Does it mean that the only way that equation can be solved is by "extending" rs
to a pair of (rs, xs)
? In other words, fold
accumulates into tuple rather than a single type (ignoring the fact that tuple itself is a single type)? Is there any other way to generalize bypassing pairing?