I'm currently at 6th chapter of Learn you a Haskell... Just recently started working my way on 99 questions.
The 3rd problem is to find the K'th element of a list. I've implemented it using take
and zip
.
The problem I have is understanding the alternate solution offered:
elementAt''' xs n = head $ foldr ($) xs
$ replicate (n - 1) tail
I'm "almost there" but I don't quite get it. I know the definition of the $
but.. Can you please explain to me the order of the execution of the above code. Also, is this often used as a solution to various problems, is this idiomatic or just... acrobatic ?
If you expand the definition of foldr
foldr f z (x1:x2:x3:...:[]) = x1 `f` x2 `f` x3 `f`... `f` z
you see that elementAt'''
becomes
elementAt''' xs n = head (tail $ tail $ ... $ tail $ xs)
(note: it should be replicate n tail
instead of replicate (n-1) tail
if indexing is 0-based).
So you apply tail
to xs
the appropriate number of times, which has the same result as drop (n-1) xs
if xs
is long enough, but raises an error if it's too short, and take the head
of the resulting list (if xs
is too short, that latter would also raise an error with drop (n-1)
).
What it does is thus
n-1
times altogether)head
of the resulting listAlso, is this often used as a solution to various problems, is this idiomatic or just... acrobatic
In this case, just acrobatic. The foldr
has to expand the full application before it can work back to the front taking the tail
s, thus it's less efficient than the straightforward traversal.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With