I want to find all prime factors of a given number using only list comprehension method and/or .
(function composition operator) in Haskell. I specifically want to
Here's how I'd do it:
pfactors :: Integer -> [Integer]
pfactors n = [ p
| p <- [2..n] -- Possible factors
, [d | d <- [1..p], p `mod` d == 0] == [1,p] -- Are prime
, _ <- [ p | i <- [1..n], n `mod` p^i == 0] ] -- Divisible powers
It's essentially the solution you have, but the difference is that it has an extra list comprehension at the end which contains as many elements as p
factors into n
.
Disclaimer I really wouldn't do it like this in reality.
EDIT I felt dirty writing the above, so for reference, this is something closer to what I would write:
pfactors' :: Int -> [Int]
pfactors' = unfoldr firstFactor
where
firstFactor n =
listToMaybe [(f, n `div` f)
| f <- [2..n]
, n `mod` f == 0]
Dependencies: Data.List (unfoldr)
, Data.Maybe (listToMaybe)