I was under the impression that foldright
starts from the end of a list and works backwards (this is how I imagined what right-associative means). So I am confused that the following works for infinite lists.
I have a function find
:
find :: (a -> Bool) -> List a -> Optional a
find p = foldRight (\c a -> if p c then Full c else a) Empty
Note that the following work:
>> find (const True) infinity
Full 0
I did do some searching and found this post: How do you know when to use fold-left and when to use fold-right?
Unfortunately, the accepted answer is not particularly helpful because the example for right-associative operations is:
A x (B x (C x D))
Which still means it needs to execute the right-most thing first.
I was wondering if anyone can clear this up for me, thanks.
A
is only evaluated if necessary. – 4castleA x (B x (C x D))
which still means it needs to execute the right-most thing first.". (Here I assume by "right-most thing" you meanD
, or possiblyC x D
.) This appears to be the fundamental mistake you've made in your reasoning. – Daniel WagnerA x (B x (C x D))
, you can evaluateA
beforeB x (C x D)
, and if you know thatA
provides the answer you never need to evaluateB x (C x D)
. (Consider for example0 * (123456789 * (890123456 * 789123456))
, which you can immediately see is0
.) – molbdnilo