Using foldr to append two lists together (Haskell)
Posted
by
Luke Murphy
on Programmers
See other posts from Programmers
or by Luke Murphy
Published on 2012-11-04T12:56:57Z
Indexed on
2012/11/04
17:16 UTC
Read the original article
Hit count: 209
I have been given the following question as part of a college assignment. Due to the module being very short, we are using only a subset of Haskell, without any of the syntactic sugar or idiomatic shortcuts....I must write:
append xs ys : The list formed by joining the lists xs
and ys
, in that order
append (5:8:3:[]) (4:7:[]) => 5:8:3:4:7:[]
I understand the concept of how foldr works, but I am only starting off in Functional programming. I managed to write the following working solution (hidden for the benefit of others in my class...) :
However, I just can't for the life of me, explain what the hell is going on!? I wrote it by just fiddling around in the interpreter, for example, the following line :
foldr (\x -> \y -> x:y) [] (2:3:4:[])
which returned [2:3:4]
, which led me to try,
foldr (\x -> \y -> x:y) (2:3:4:[]) (5:6:7:[])
which returned [5,6,7,2,3,4]
so I worked it out from there. I came to the correct solution through guess work and a bit of luck...
I am working from the following definition of foldr:
foldr = \f -> \s -> \xs -> if null xs then
s
else
f (head xs) (foldr f s (tail xs) )
Can someone baby step me through my correct solution? I can't seem to get it....I already have scoured the web, and also read a bunch of SE threads, such as How foldr works
© Programmers or respective owner