I am very new to Haskell and i thought that to get a hang of writing haskell programs,i might solve some project euler problems.
So i went on with it and implemented the problem number 4 of Project Euler.
The problem Statement:
A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
Find the largest palindrome made from the product of two 3-digit numbers.
But there seems to be something wrong with my solution.
Here it is:
projectEuler4 :: (Ord a,Num a) => a
projectEuler4 = max palindromeList
where palindromeList = [reverse(x*y)|x<-[1..999],y <- [1..999]]
GHCI gives me this error:
ProjectEuler4.hs:2:17:
Could not deduce (a ~ ([[a0]] -> [[a0]]))
from the context (Ord a, Num a)
bound by the type signature for
projectEuler4 :: (Ord a, Num a) => a
at ProjectEuler4.hs:1:18-35
`a' is a rigid type variable bound by
the type signature for projectEuler4 :: (Ord a, Num a) => a
at ProjectEuler4.hs:1:18
In the return type of a call of `max'
Probable cause: `max' is applied to too few arguments
In the expression: max palindromeList
In an equation for `projectEuler4':
projectEuler4
= max palindromeList
where
palindromeList
= [reverse (x * y) | x <- [1 .. 1000], y <- [1 .. 1000]]
I dont know what this means and am frustrated for not finding the reason for the error. Any help will be appreciated.Thanks.
So After reading some of the answers and comments, i did something like This:
projectEuler4 :: (Ord a,Num a) => a
projectEuler4 = max' palindromeList
where palindromeList = [reverse(show(x*y))|x<-[1..999],y <- [1..999]]
max' :: (Ord a) => [a] -> a
max' [] = error "Empty List"
max' [p] = p
max' (p:ps) = max p (max' ps)
Still doesn't work.
OK..
BY following @bheklilr's advice, i changed my program:
products :: [Integer] -> [Integer] -> [Integer]
products ns ms = [x * y | x <- ns, y <- ms]
isPalindrome :: Integer -> Bool
isPalindrome n = let s = show n in s == reverse s
palindromes :: [Integer]
palindromes = maximum filter (isPalindrome "") (products [100..999] [100..999])
Now what do i put in place of the inverted comma? I am seriously confused.
max(palindromeList)
. Trymax palindromList
, without the parentheses. Haskell doesn't use C-style calling conventions. – crockeea(((5))) + 4
:) – Will Nessmax
works on two numbers, not a list (though it would be reasonable to work on lists as well). You can find out information like this using GHCi:t max
, or using Hoogle. – crockeea