Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the K'th element of a list using foldr and function application ($) explanation

Tags:

haskell

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 ?

like image 765
Ivan Davidov Avatar asked Jan 25 '13 16:01

Ivan Davidov


1 Answers

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

  • discard the first element of the list
  • discard the first element of the resulting list (n-1 times altogether)
  • take the head of the resulting list

Also, 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 tails, thus it's less efficient than the straightforward traversal.

like image 80
Daniel Fischer Avatar answered Oct 09 '22 10:10

Daniel Fischer