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
foldryou see that
elementAt'''becomes(note: it should be
replicate n tailinstead ofreplicate (n-1) tailif indexing is 0-based).So you apply
tailtoxsthe appropriate number of times, which has the same result asdrop (n-1) xsifxsis long enough, but raises an error if it’s too short, and take theheadof the resulting list (ifxsis too short, that latter would also raise an error withdrop (n-1)).What it does is thus
n-1times altogether)headof the resulting listIn this case, just acrobatic. The
foldrhas to expand the full application before it can work back to the front taking thetails, thus it’s less efficient than the straightforward traversal.