Implementing a factorisation method in Haskell

微笑、不失礼 提交于 2019-12-08 15:26:29

for some code golf i wrote a nice power set function that is pretty simple.

powerSet [] = []
powerSet (x:xs) = xs : map (x:) (powerSet xs) ++ (powerSet xs)

A deficiency of this algorithm is that it doesn't include the original set, however that is perfect for you since it doesn't look like you want it.

combine this with a way to convert your primePowerFactors n into a list of ints, lets say

ppfToList = concatMap (\(x,y)->replicate y x)

using these helpers, a list of factors from a number n is generated with

factors n = nub . map product . powerSet . ppfToList . primePowerFactors $ n
-- will be out of order, you can add a call to `sort` to fix that

This sort of algorithm is probably a bit harder to express in terms of a list comprehension.

First of all, facs is the identity function:

facs (x,y) = (x,y)

The y is bound in the pattern match on the left hand side while you probably intended it to be the y from the list comprehension. Variable names bound in a list comprehension are local to that comprehension and can not be used in a different scope like the where clause.

Also, the y in the list comprehension is only computed from the last factors exponent:

y <- [0..(snd $ last $ primePowerFactors n)]

For each factor it's own exponent should be considered, not just always the exponent of the last factor.

A more fundamental problem is, that the return type of the factors function doesn't seem to match it's intention:

*Euler> :t factors
factors :: Integer -> [(Integer, Int)]

This returns a list of powers of prime factors while it should produce a list of these constructs, like this:

[
   [(2,0), (7,0)],
   [(2,1), (7,0)],
   [(2,2), (7,0)],
   [(2,0), (7,1)],
   [(2,1), (7,1)],
   ...
]

The prime factorization of all possible factors is needed, but the function seems to return just one prime factorization.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!