1
module PRO where
average1 :: IO Float
avarage1  =
    do
        putStrLn "Enter Marks in Form of a List"
        marks <- getLine
        let m = (read marks)::[Int]
        x<-(sum' (m)) 
        avg <- x/length (m)
        if(x/=[])
           then
                putStrLn ("empty List")
            else
                putStrLn ("Your Avarage is " ++ show(avg))


sum' :: (Num a) => [a] -> a
sum' xs = foldl (\acc x -> acc + x) 0 xs

My program doesn't seems to work! My question is why can't I assign avg the returning sum of the sum' function?

2 Answers 2

6
module PRO where

average1 :: IO ()
average1 =
    do
        putStrLn "Enter Marks in Form of a List"
        marks <- getLine
        let m = (read marks)::[Int]
        let x = sum' m 
        let avg = (fromIntegral x)/(fromIntegral $ length m)
        if(m==[])
            then
                putStrLn ("empty List")
            else
                putStrLn ("Your Avarage is " ++ (show avg))

sum' :: (Num a) => [a] -> a
sum' xs = foldl (\acc x -> acc + x) 0 xs

i) The type signature of average1 is incorrect, the function does not return a value

ii) [Edit: this point was incorrect]

iii) the average value is a float, so you need to cast the integer arguments

iv) Your test if (x/=[]) is the wrong way round and should use m not x

v) most of your lines are not in the IO monad and so should use let inside a do block

Sign up to request clarification or add additional context in comments.

2 Comments

MacPhail thanks a lot for your help. The code compiled no problem but i still get a run time error saying PRO> average1 Enter Marks in Form of a List [1,2,3] Your Avarage is Program error: Prelude.read: no parse
@jwodder @Vivian McPhail got it, thanks for the help you guys provided. you rock!
5

You can't use the <- notation for assigning the return values of sum' m and x/length m. <- can only be used when the right-hand side is a monadic expression (in this case, an IO value), which neither one is, and so you should use let x = sum' m and let avg = x / fromInteger (length m) instead (fromInteger is needed to convert the Int returned by length m to a Fractional value so it can be passed to /). (Also, you need to change x /= [] to m /= [].)

2 Comments

thanx jwodder! but i still can not let calculate the average i getting error ERROR file:.\PRO.hs:10 - Type error in application *** Expression : fromInteger (length m) *** Term : length m *** Type : Int *** Does not match : Integer
@visuddha use fromIntegral to coerce integral types.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.