[Haskell-beginners] Re: question about styles of recursion
daniel.is.fischer at web.de
Thu Mar 26 17:10:45 EDT 2009
Am Donnerstag 26 März 2009 21:53:47 schrieb 7stud:
> 7stud <bbxx789_05ss <at> yahoo.com> writes:
> > > myAvg' :: Int -> [Int] -> [ Double ] -> Double
> > > myAvg' sum count  = sum / fromIntegral count
> > > myAvg' sum count (x:xs) = myAvg' (x + sum) (n + 1) xs
> > The length function was introduced
> > before the sum function, which I see you are using in your
> > function definition.
> Hmm...I guess you aren't using the sum function--that's one
> of your variable names. I wonder how Prelude knows sum
> is a variable name and not the sum function?
Name shadowing/scoping. By naming one of the parameters sum, a
local variable with that name is declared and Prelude.sum is only
accessible qualified in that scope. It's the same as declaring local
variables with the same name as one in an enclosing scope in other
> I changed the
> name sum to s, and I get this error:
> Prelude Data.List> :load ehask.hs
> [1 of 1] Compiling Main ( ehask.hs, interpreted )
> 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
More information about the Beginners