[Haskell-beginners] foldr on infinite list to decide prime number
cwyang at aranetworks.com
Tue Feb 2 02:12:35 UTC 2016
Aha! I see.
Thank you for pointing the short-circuiting of (||),
and for nice article.
2016-02-02 11:01 GMT+09:00 Francesco Ariis <fa-ml at ariis.it>:
> On Tue, Feb 02, 2016 at 10:32:10AM +0900, Chul-Woong Yang wrote:
>> Hi, all.
>> While I know that foldr can be used on infinite list to generate infinite
>> 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?
> 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 . 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).
>  http://ariis.it/static/articles/haskell-laziness/page.html (more
> complex cases section)
> Beginners mailing list
> Beginners at haskell.org
More information about the Beginners