HNHacker News
TopNewBestAskShowJobs

plingbang

75 karma · joined February 13, 2021

submissionscomments
plingbang··on Ask HN: What piece of code/codebase blew your mind when you saw it?
A version that should confuse people not familiar with Haskell even more:

    primes = 2 : filter isPrime [3..]
    isPrime x = all (\p -> x `mod` p /= 0) $ takeWhile (\p -> p * p <= x) primes
primes is a list of prime numbers. It is defined as number 2 and numbers 3,4,5... for which isPrime is True.

isPrime is a function that checks that x is a prime number by taking numbers whose squares don't exceed x from... primes list... and then making sure they all divide x with a reminder.

It only works because isPrime never touches an unevaluated element of primes list. Otherwise, the program would loop.

← PreviousPage 2 of 2