Reputation: 1161
I'm stuck on this problem and I'm very new to Haskell, I was trying to complete the first Euler problem with the following code:
main = putStrLn . show . sum $ [3,6..1000]:[5,10..1000]
And here's the first part of the error:
euler/1.hs:1:19:
No instance for (Show t0) arising from a use of `show'
The type variable `t0' is ambiguous
Possible fix: add a type signature that fixes these type variable(s)
Note: there are several potential instances:
instance Show Double -- Defined in `GHC.Float'
instance Show Float -- Defined in `GHC.Float'
instance (Integral a, Show a) => Show (GHC.Real.Ratio a)
-- Defined in `GHC.Real'
...plus 23 others
In the first argument of `(.)', namely `show'
In the second argument of `(.)', namely `show . sum'
In the expression: putStrLn . show . sum
Upvotes: 3
Views: 1339
Reputation: 9891
Unfortunately the error message you get is missing the problem. Loading it in ghci 7.4.2 gives much more helpful error messages:
No instance for (Num [t0])
arising from a use of `sum'
Possible fix: add an instance declaration for (Num [t0])
In the second argument of `(.)', namely `sum'
In the second argument of `(.)', namely `show . sum'
In the expression: putStrLn . show . sum
No instance for (Enum [t0])
arising from the arithmetic sequence `5, 10 .. 1000'
Possible fix: add an instance declaration for (Enum [t0])
In the second argument of `(:)', namely `[5, 10 .. 1000]'
In the second argument of `($)', namely
`[3, 6 .. 1000] : [5, 10 .. 1000]'
In the expression:
putStrLn . show . sum $ [3, 6 .. 1000] : [5, 10 .. 1000]
This seems to hint that the problem is in the expression [3, 6 .. 1000] : [5, 10 .. 1000]
and indeed it is because the type of :
is a -> [a] -> [a]
and x:xs
simply adds the element x
to the beginning of the list xs
. In [3, 6 .. 1000] : [5, 10 .. 1000]
you are trying to add [3, 6 .. 1000]
as an element to [5, 10 .. 1000]
, but lists in haskell must contain elements of the same type (they are homogeneous) so that will not work. This is because [3, 6 .. 1000]
has the type [Int]
and the elements of [5, 10 .. 1000]
has the type Int
.
I think that what you are looking for is ++
which has the type [a] -> [a] -> [a]
and xs ++ ys
is the concatenation of the list xs
and the list ys
:
ghci> putStrLn . show . sum $ [3,6..1000] ++ [5,10..1000]
267333
Upvotes: 4
Reputation: 3770
What do you expect [3,6..1000]:[5,10..1000]
to do? x : xs
preppeds an object to a list of objects. Here both arguments are lists of integers. Did you want ++
instead (concatenation).
It needs to be said that your approach is not right, no matter what you expected :
to do. I'll not expand on this in case you want to figure it out yourself.
Upvotes: 6