[Haskell-beginners] foldr on infinite list to decide prime number
tkoster at gmail.com
Wed Feb 3 01:59:09 UTC 2016
On 3 February 2016 at 11:52, derek riemer <driemer.riemer at gmail.com> wrote:
> Doesn't foldr have to "reach" to the far right of the list of infinite
> primes to get the last number since it consumes from the right?
foldr does not consume from the right. It is right-associative.
See these simulations:
Notice that the essential difference between foldr and foldl is the
placement of the parentheses in the result, which the simulations show
very well. Whether that expression "short-circuits" or not depends on
the operator you used with your fold. Operators that are lazy in their
second argument (at least some of the time), like "||" and ":", can
short-circuit when used with foldr.
A common mistake is to think the parentheses force an evaluation
order, like "inside-out" for example. This is not the case for lazy
languages like Haskell. This unfortunate confusion probably arises
because parentheses often do prescribe evaluation order in basic
arithmetic and strict languages like Java.
Hope this helps,
More information about the Beginners