[Haskell-beginners] Re: question about styles of recursion
Daniel Fischer
daniel.is.fischer at web.de
Thu Mar 26 23:42:52 EDT 2009
Am Freitag 27 März 2009 03:37:27 schrieb 7stud:
> Daniel Fischer <daniel.is.fischer <at> web.de> writes:
> > > myAvg' :: Int -> [Int] -> [ Double ] -> Double
> > >
> > > myAvg' sum count [] = sum / fromIntegral count
> > > myAvg' sum count (x:xs) = myAvg' (x + sum) (n + 1) xs
> > >
> > >
> > > ehask.hs:2:24:
> > > Couldn't match expected type `Double' against inferred type
`Int'
> > > In the expression: s / fromIntegral count
> > > In the definition of `myAvg'':
> > > myAvg' s count [] = s / fromIntegral count
> > > Failed, modules loaded: none.
> >
> > Yup, the type signature is wrong, it should be
> >
> > myAvg' :: Double -> Int -> [Double] -> Double
>
> Can you explain the error message in detail? To me it looks like
> this should be the problem:
>
> Prelude> fromIntegral [1, 2, 3]
>
> <interactive>:1:0:
> No instance for (Integral [t])
> arising from a use of `fromIntegral' at <interactive>:1:0-21
> Possible fix: add an instance declaration for (Integral [t])
> In the expression: fromIntegral [1, 2, 3]
> In the definition of `it': it = fromIntegral [1, 2, 3]
>
That would be the next problem.
By the type signature, the result of myAvg' is a Double, hence the use
of (/) in the first equation is at type Double -> Double -> Double.
Now the first argument of (/) is s(um), which by the type signature is of
type Int, while (/) expects Double.
So, expected type is Double, 'inferred' (from the type signature) type
is Int, doesn't match, boom.
The compiler stops there, if it didn't, it would also report the missing
instance for (Integral [Int]).
More information about the Beginners
mailing list