<html>
<head>
<meta content="text/html; charset=windows-1252"
http-equiv="Content-Type">
</head>
<body bgcolor="#FFFFFF" text="#000000">
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?<br>
<br>
<div class="moz-cite-prefix">On 2/1/2016 7:01 PM, Francesco Ariis
wrote:<br>
</div>
<blockquote cite="mid:20160202020123.GA29140@casa.casa" type="cite">
<pre wrap="">On Tue, Feb 02, 2016 at 10:32:10AM +0900, Chul-Woong Yang wrote:
</pre>
<blockquote type="cite">
<pre wrap="">Hi, all.
While I know that foldr can be used on infinite list to generate infinite
list,
I'm having difficulty in understaind following code:
isPrime n = n > 1 && -- from haskell wiki foldr (\p r -> p*p > n || ((n
`rem` p) /= 0 && r)) True primes primes = 2 : filter isPrime [3,5..]
primes is a infinite list of prime numbers, and isPrime does foldr to get a
boolean value.
What causes foldr to terminate folding?
</pre>
</blockquote>
<pre wrap="">
foldr _immediately_ calls the passed function, hence /it can short
circuit/, that isn't the case for foldl.
I wrote an article to explain it [1]. It was drafted in a time when
foldr and friends were monomorphic (i.e. they only worked with lists),
but it should illustrate the point nicely.
Current polymorphic implementation of foldr is:
foldr :: (a -> b -> b) -> b -> t a -> b
foldr f z t = appEndo (foldMap (Endo #. f) t) z
and I must admit I have problems explaining why it terminates
early (as it does).
[1] <a class="moz-txt-link-freetext" href="http://ariis.it/static/articles/haskell-laziness/page.html">http://ariis.it/static/articles/haskell-laziness/page.html</a> (more
complex cases section)
_______________________________________________
Beginners mailing list
<a class="moz-txt-link-abbreviated" href="mailto:Beginners@haskell.org">Beginners@haskell.org</a>
<a class="moz-txt-link-freetext" href="http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners">http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners</a>
</pre>
</blockquote>
<br>
<div class="moz-signature">-- <br>
<hr>
<h2 style="text-size:24px;"> Derek Riemer </h2>
<ul>
<li> Department of computer science, third year undergraduate
student. </li>
<li> Proud user of the NVDA screen reader.</li>
<li> Open source enthusiast.</li>
<li> Member of Bridge Cu </li>
<!-- <li> Member of the Council for Inclusion, Leadership, and advocacy. </li> -->
<li> Avid skiier.</li>
</ul>
<p> Websites: <br>
<a href="http://derekriemer.com">Honors portfolio</a> <br>
<a href="http://django.derekriemer.com/weather/">Awesome little
hand built weather app!</a> <br>
</p>
<p>
<a href="mailto:derek.riemer@colorado.edu"> email me at
derek.riemer@colorado.edu</a>
<br>
Phone: (303) 906-2194
</p>
</div>
</body>
</html>