[Haskell-beginners] foldr with ($) as the passed function

Ut Primum utprimum at gmail.com
Thu Jan 14 07:16:04 UTC 2021


Hi,

I think your interpretation of (replicate (n-1) tail) is wrong. First note
that tail is not applied to anything, is just the function tail.
So replicate (n-1) tail is [tail, tail, tail, .... , tail]. For example
replicate 3 tail = [tail, tail, tail]
Note that if you try to compute this in Haskell it won't be able to show
that result, because there is no "show" defined for something that has the
type of a list of functions.

Having said this, your example can now be written
elementAt [1,2] 2 =
= head (foldr ($) [1,2] (replicate 1 tail))
= head (foldr ($) [1,2] [tail])
= head (tail $ (foldr ($) [1,2] []))
= head (tail $ [1,2])
= head (tail ([1,2])) = head [2] = 2

For a more general example you can try

elementAt [1,2,3,4] 3 =
= head (foldr ($) [1,2,3,4] (replicate 2 tail))
= head (foldr ($) [1,2,3,4] [tail,tail])
= head (tail $ (foldr ($) [1,2,3,4] [tail]))
= head (tail $ tail $ [1,2,3,4])
= head (tail (tail [1,2,3,4)))
= head (tail [2,3,4]) = head [3,4] = 3

Cheers,
Ut

<http://www.avg.com/email-signature?utm_medium=email&utm_source=link&utm_campaign=sig-email&utm_content=webmail>
Mail
priva di virus. www.avg.com
<http://www.avg.com/email-signature?utm_medium=email&utm_source=link&utm_campaign=sig-email&utm_content=webmail>
<#DAB4FAD8-2DD7-40BB-A1B8-4E2AA1F9FDF2>

Il giorno gio 14 gen 2021 alle ore 07:25 Lawrence Bottorff <
borgauf at gmail.com> ha scritto:

> With 99 questions <https://wiki.haskell.org/99_questions/Solutions/3> Problem
> 3 wants a function elementAt that will take a list and an index and return
> the element for that index. One very odd version in the solutions is
>
> elementAt xs n = head $ foldr ($) xs $ replicate (n - 1) tail
>
> So the function "passed" is ($) and the accumulator "seed" is the incoming
> list xs and the list to be worked on is (replicate (n-1) tail) which . . .
> and I can't fathom what's happening -- other than perhaps (replicate (n-1)
> (tail xs))
>
> elementAt [1,2] 2 would be
>
> foldr ($) [1,2] (replicate 1 (tail [1,2])
> foldr ($) [1,2] ([2])
>
> . . . now I'm lost. Can someone walk me through this?
>
> LB
> _______________________________________________
> Beginners mailing list
> Beginners at haskell.org
> http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.haskell.org/pipermail/beginners/attachments/20210114/03a770bd/attachment.html>


More information about the Beginners mailing list