Thursday, 4th March, 2010
Faffing with Haskell
Recently, there’s been a peak in the relative interest in languages such as Haskell, Scala, Erlang and Lisp-Like languages. Primarily because there’s a fresh interest in functional languages in general. Obviously, I thought I’d give it a poke.
Personally, I thought it would be a good idea to try and do some Eulering in it. It’s list comprehension syntax is very close to that of Python’s, however, it’s type strictness seems a little extreme at this point. Ahh well, growing pains. Where would we be without them?
Problem 1
Simplistic and easy:
sum [n | n <- [1..999], n `mod` 3 == 0 || n `mod` 5 == 0]
Very, very similar to the Python variation.
Problem 5
Once again, a very simple problem, and a very similar solution to the Python solution.
foldr (\a b -> (a*b) `div` (gcd a b)) 1 [1..20]
Problem 20
Decided to not try to get around the type system in order to do this one. I decided to actually form a list of integers from an integer the “correct”, mathematical way; as opposed to bodging my way through a type system.
factorial :: Integer -> Integer factorial n = product [1..n] listFromInteger :: Integer -> [Integer] listFromInteger 0 = [] listFromInteger n = (n `mod` 10) : listFromInteger ((n - (n `mod` 10)) `div` 10) main = do putStrLn (show (sum $ listFromInteger $ factorial 100))
I swish my mathematical-ness at you!
Problem 29
Once again, vastly similar code…
import Data.Set exponents :: (Integral a) => a -> Set a exponents n = Data.Set.fromList [(\a b -> a^b) a b | a <- [2..n], b <- [2..n]] main = do putStrLn (show (Data.Set.size $ exponents 100))
Meh.
Problem 45
Yet again, nearly identical code. Runs marginally faster, if my memory serves me well.
import Data.Set hexs = Data.Set.fromList [(\n -> 2*n*(2*n - 1)) n | n <- [1..1000000]] pent = Data.Set.fromList [(\n -> n*(3*n - 1)) n | n <- [1..1000000]] main = do putStrLn (show (Data.Set.map (`div` 2) (Data.Set.intersection hexs pent)))
Only major difference to note here is that a set is not a built in primitive, but found in a library. Not really a major issue.
Done! :-D