Razvan Meriniuc
Razvan Meriniuc

Reputation: 182

Code meaning in Haskell 99 problems

I have been working on the 99 Haskell problems challenge and one of the solutions of problem no. 3 - Get the k-th element of a list, counting from 1, not 0 - is:

elementAt''' xs n = head $ foldr ($) xs $ replicate (n - 1) tail

I understand that, given a list, we could perform (n - 1) tail operations and the first element of the final list is the one we are looking for. As it is written, the foldr's accumulator's initial value is the given list, but I fail to identify the second argument, which should be a list, right?

I would appreciate if you explained the first steps foldr makes.

Upvotes: 1

Views: 116

Answers (1)

sepp2k
sepp2k

Reputation: 370425

The list argument is replicate (n - 1) tail, which is a list that contains the function tail (n-1) times. So we have ($) as the function, xs as the initial element and [tail, tail, ..., tail] as the list. So the result of the fold is tail $ tail $ ... $ tail $ xs.

Upvotes: 4

Related Questions