[Haskell-beginners] foldr on infinite list to decide prime number

Chul-Woong Yang cwyang at aranetworks.com
Wed Feb 3 00:36:00 UTC 2016


Thank you for kind response.

See you in another thread. :-)

2016-02-02 22:33 GMT+09:00 Gesh <gesh at gesh.uni.cx>:
> On February 2, 2016 3:36:03 AM GMT+02:00, Chul-Woong Yang <cwyang at aranetworks.com> wrote:
>>I feel sorry for posting mis-formatted code.
>>I re-post the question.
>>--
>>
>>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?
>>
>>Any helps will be deeply appreciated.
>>
>>Thank you.
>>
>>
>>2016-02-02 10:32 GMT+09:00 Chul-Woong Yang <cwyang at aranetworks.com>:
>>
>>> 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?
>>>
>>> Any helps will be deeply appreciated.
>>>
>>> Thank you.
>>>
>>> Chul-Woong
>>>
>>
>>
>>------------------------------------------------------------------------
>>
>>_______________________________________________
>>Beginners mailing list
>>Beginners at haskell.org
>>http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners
>
> Note that || is lazy, specifically:
>> True || _ = True
>> False || x = x
> Hence, once foldr reaches a prime larger than sqrt n, the first branch of || will be True, short-circuiting the entire infinite computation.
>
> HTH,
> Gesh
> _______________________________________________
> Beginners mailing list
> Beginners at haskell.org
> http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners


More information about the Beginners mailing list