Reputation: 462
I have this code which generates prime numbers from 2 to n
primes :: Integer -> [Integer]
primes n = sieve [2..n]
where
sieve (p:xs) = p : sieve [x|x <- xs, x `mod` p > 0]
How do I pass the sieve
d list (which has my primes) to another function?
Something like this doesn't work (parse error)
someText:: [Integer] -> String
someText (x:[]) = "List starts with" ++ show x
primes :: Integer -> [Integer]
primes n = sieve [2..n]
where
sieve (p:xs) = p : sieve [x|x <- xs, x `mod` p > 0]
someText sieve
Upvotes: 1
Views: 549
Reputation: 120711
You don't pass something to a function, like some list. That's imperative thinking. What you do in Haskell is, you evaluate some function with e.g. a list as its argument. Normally, you'd just leave primes
as it is and use the result as the argument for someText
. Like†,
main :: IO ()
main = print (someText $ primes 100)
or simply in the REPL
GHCi> someText $ primes 100
"List starts with2"
Of course, you can also redefine primes
to include someText
. But obviously, the result will then be a string and not a list anymore!
primes' :: Integer -> String
primes' n = someText $ sieve [2..n]
where sieve (p:xs) = p : sieve [x|x <- xs, x `mod` p > 0]
It's probably better not to do this, because such a string is pretty useless when you want to use the prime list in any other way. You can better just invoke the original primes
function:
primes' :: Integer -> String
primes' = someText . primes
†Actually this doesn't work: your function someText
isn't complete. The pattern x:[]
only matches a list which has exactly one element (this is more handily written someText [x] = ...
). You want to match on any list which starts with one element; do that with the pattern x:_
.
Upvotes: 3