We can take a look at an example. For example if we have a list [1, 4, 2, 5]
. If we thus process the list, then we see that foldr
will be calculated as:
foldr (\a ~(x,y) -> (a:y,x)) ([],[]) [1,4,2,5]
So here a
is first the first item of the list, and then it will tus return something like:
(1:y, x)
where (x, y) = foldr (\a ~(x,y) -> (a:y,x)) ([],[]) [4,2,5]
Notice that here the (x, y)
tuple is swapped when we prepend a
to the first item of the 2-tuple.
(1:y, x)
where (x, y) = (4:y', x')
(x', y') = foldr (\a ~(x,y) -> (a:y,x)) ([],[]) [2,5]
and if we keep doing that, we thus obtain:
(1:y, x)
where (x, y) = (4:y', x')
(x', y') = (2:y'', x'')
(x'', y'') = (5:y''', x''')
(x''', y''') = foldr (\a ~(x,y) -> (a:y,x)) ([],[]) []
Since we reached the end of the list, we thus obtain for the foldr … ([], []) []
, the 2-tuple ([], [])
:
(1:y, x)
where (x, y) = (4:y', x')
(x', y') = (2:y'', x'')
(x'', y'') = (5:y''', x''')
(x''', y''') = ([],[])
So x''' = []
and y''' = []
, so thus this is resolved to:
(1:y, x)
where (x, y) = (4:y', x')
(x', y') = (2:y'', x'')
(x'', y'') = (5:[], [])
(x''', y''') = ([],[])
so x'' = [5]
and y'' = []
:
(1:y, x)
where (x, y) = (4:y', x')
(x', y') = (2:[], [5])
(x'', y'') = (5:[], [])
(x''', y''') = ([],[])
so x' = [5]
and y' = [2]
:
(1:y, x)
where (x, y) = (4:[5], [2])
(x', y') = (2:[], [5])
(x'', y'') = (5:[], [])
(x''', y''') = ([],[])
so x = [4, 5]
and y = [2]
so eventually we obtain:
(1:[2], [4,5])
where (x, y) = (4:[5], [2])
(x', y') = (2:[], [5])
(x'', y'') = (5:[], [])
(x''', y''') = ([],[])
so the result is the expected ([1,2], [4,5])
.