Haskell learning exercise gives strange results

haskell

Solution

You get the wrong answers for your first attempt, because you use an incorrect formula. Garbage in, garbage out. (Other people have covered this.)

You are probably getting a parse error because some lines are using spaces and others are using tabs. Or you are using all tabs, but with a non-standard tab width.

No indentation is used or required here, so the spaces -v- tabs issue doesn't arise.

Problem

this is the question: "Write a function that computes the mean of a list, i.e. the sum of all elements in the list divided by its length. (You may need to use the fromIntegral function to convert the length of the list from an integer into a floating point number.)" first i tried this: ``` mean :: [Double] -> Double mean [] = 0 mean (x:xs) = (x + mean xs) / (1 + mean xs) ``` but it give me strange results, for example, when i use it like that: ``` mean [2,4,6] ``` it give me the result: 1.41176 where it should be: 4 why? i tried another thing: ``` mean :: [Double] -> Double mean list = (summ list) / (count list) where count [] = 0 count (x:xs) = 1 + count xs summ [] = 0 summ (x:xs) = x + summ xs ``` but i have an error when i tried to load the file into GHC. the error is: ``` parse error on input 'count' Failed, modules loaded: none ``` again, what am i doing wrong? at last, i tried this one (that succeeded): ``` mean :: [Double] -> Double count [] = 0 count (x:xs) = 1 + count xs summ [] = 0 summ (x:xs) = x + summ xs mean list = summ list / count list ``` it's the same as the above one (with the 'where' keyword), but it succeed only here, and not in the above one. why? thanks a lot. p.s. i'm learning from the book -- Real World Haskell and the exercise is from here -- (roll it down :-)) thanks to you all. it's a strange thing. the second example also work for me too when i copied it from here and tested it. i don't know why it didn't work for me yesterday :-) but i still don't understand why the first one doesn't work. i think it should be like that ``` (2 + mean [4,6]) / (1 + mean [4,6]) (4 + mean [6 ]) / (1 + mean [ 6]) (6 + mean [ ]) / (1 + mean [ ]) ``` so now it is like that ``` (6 + 0 ) / (1 + 0 ) -- last recursion (4 + (6 + 0) ) / (1 + (1 + 0) ) (2 + (4 + (6 + 0))) / (1 + (1 + (1 + 0)) ``` so now it should be: 12 / 3 isn't it? what i don't understand? thank you :-).

Original source