Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I properly use the length function in haskell?

I am currently working on trying to find the number of primes between a range in haskell. The program prints out the range of primes correctly. E.g countPrimesUntil 2 10 will print out [2, 3, 5, 7]. I am looking for the number 4 because that’s how many primes is between 2 and 10. How do I incorporate countPrimes correctly?

import Data.List

countPrimesUntil :: Integral a=> a -> a -> [a]
countPrimesUntil a b = takeWhile (<= b) $ dropWhile (< a) $ sieve [2..]
    while sieve (n:ns) = n:sieve [m | m <- ns, m `mod` n /= 0]

countPrimes n = length([x | x <- [2..n], countPrimesUntil x])

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

countPrimesUntil is misnamed; it doesn’t count anything. Rather, it produces a list of primes between a and b, inclusive.

All you need to do is apply length to the result of countPrimesUntil, when given arguments 2 and n.

countPrimes n = length (countPrimesUntil 2 n)
-- countPrimes = length . countPrimesUntil 2
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading