user3389445
user3389445

Reputation:

Counting all prime number in Haskell

I'm trying to create a function in Haskell that counts all prime numbers, but it doesn't seem to work. This is how my code looks like:

import Data.Char
countPrimeNumbers :: [Int] -> Int
countPrimeNumbers n = all (isDigit) n

Anyone has a solution to this? Thanks!

Upvotes: 0

Views: 950

Answers (3)

karakfa
karakfa

Reputation: 67467

This will give you the list of primes (import Data.List)

nubBy (\x y -> x `mod` y == 0) [2..]

Upvotes: 0

bheklilr
bheklilr

Reputation: 54058

What you're wanting is something like

countPrimes :: [Int] -> Int
countPrimes ns = length $ filter isPrime ns

But you'll have to come up with isPrime on your own


The all function has the type

all :: (a -> Bool) -> [a] -> Bool

What it does is apply a test to every element in the list, then does a logical AND with all elements. If you wanted to test if all the elements in a list were prime, you could use it as

allPrime :: [Int] -> Bool
allPrime ns = all isPrime ns

where

isPrime :: Int -> Bool
isPrime n = undefined -- Test if its a prime here

The filter function, by contrast, takes the same kind of predicate, but returns only the values that pass the predicate, for example:

> :type even
Int -> Bool
> even 1
False
> even 2
True
> filter even [1..10]
[2, 4, 6, 8, 10]

So filter isPrime ns should return all the numbers in ns that are prime, then you just count them with length.

Upvotes: 4

Mike
Mike

Reputation: 2463

Here's a short Haskell function that enumerates primes from Literate Programs:

primes :: [Integer]
primes = sieve [2..]
  where
    sieve (p:xs) = p : sieve [x|x <- xs, x `mod` p > 0]

Apparently, this is not the Sieve of Eratosthenes (thanks, Landei). I think it's still an instructive example that shows you can write very elegant, short code in Haskell and that shows how the choice of the wrong data structure can badly hurt efficiency.

Upvotes: 1

Related Questions