I am currently reading Why Functional Programming Matters by John Hughes.
In the "Gluing Functions Together" section, after having explained that (foldr f a)
is a function that replaces all occurrences of Cons
in a list by f
, and all occurrences of Nil
by a
(which I understand), the author writes: "Now it’s obvious that (foldr Cons Nil)
just copies a list" and gives this example to illustrate the point:
append [1, 2] [3, 4] = foldr Cons [3, 4] [1, 2]
= foldr Cons [3, 4] (Cons 1 (Cons 2 Nil))
= Cons 1 (Cons 2 [3, 4]))
= [1, 2, 3, 4]
I do not understand why on the third line of the given example, (Cons 1 (Cons 2 Nil))
is suddenly at the front and consequently why the list does not end up being [3, 4, 1, 2]
. Is the Nil
in (Cons 1 (Cons 2 Nil))
a
and is Cons [3, 4]
f
if foldr
's definition is foldr f a
?
In which way is it obvious that foldr Cons Nil
just copies a list?
(foldr f a)
means "replace allCons
withf
and allNil
witha
, then replacing allCons
withCons
and replacing allNil
withNil
should leave the list looking the same as it started, right?