Paul Phillips (extempore) wrote,

do not neglect mr. euler

My friend is doing project euler in scala and he's up to #32. He's ten times the programmer I am so I had better get back to work. I did the first 46 in erlang but as of problem 47 I switched to haskell. That should mean I'd have to re-implement many of the utility functions I already wrote in erlang, except that I'm "borrowing" anything I already wrote in erlang so the language jump doesn't hurt too badly.

I'm just starting to wrap my head around haskell so if you must ridicule my code at least suggest improvements.
-- #47
p47 = p47try (map compress_factors factorizations)

p47try list = 
	if all (\x -> length x >= 4) seq &&				-- each has 4+ factors
		sum (map length seq) == length (nub $ concat seq)	-- all factors distinct
		then map unfactorize seq
		else p47try $ tail list
	where seq = take 4 list

Note that factorizations is an infinite list:
factorizations  = map factorise [2..]

compress_factors [] = []
compress_factors xs =
        (head(xs), length top) : compress_factors (drop (length top) xs)
        where top = [x | x <- xs, x == head(xs) ]

unfactorize xs =
        product [a^b | (a,b) <- xs]

That's my favorite part of haskell, that you can have data structures that represent infinite lists. Since everything is evaluated lazily, it's happy to let you work with infinite structures - but if you ask for the last element of the list you may have to wait a bit. Grab some coffee.

Sorry that some of the syntax coloring is hard to read - this is the default HsColour html output. I'll see if I can find something more readable.

Update: problem 48. One liners are nice.
-- #48
p48 = sum [x^x | x <- [1..1000] ] `mod` 10^10
  • Post a new comment

    Error

    Comments allowed for friends only

    Anonymous comments are disabled in this journal

    default userpic

    Your IP address will be recorded  

  • 6 comments