Visuddha Karunaratne
Visuddha Karunaratne

Reputation: 536

Problem with haskell programm (Type errors )

--Standered Diviation 
module SD where
diviation:: IO()
diviation = 
    do
       putStrLn ("Enter Students Marks")
       marks <- getLine
       let m = ( read marks)::[Float]
       let x = sum' m
       let mean = (fromIntegral x)/(fromIntegral $ length )
       let len = (read (length(m)))::Float
       let divia = divi mean l 
       let std = map (^2) divia
       let stdd = xx length(m-1) m
       let final = map sqrt stdd
       let tot = sum final 

       if(m==[])
              then
                putStrLn("empty List" ++ show(tot))
           else do
                putStrLn("The Standered Divation is" ++ (show(tot)))


sum' :: (Num a) => [a] -> a
sum' = foldl (+) 0

avg::Float->Float->Float
avg a b = (fromIntegral a)/(fromIntegral b)

divi::Float->[Float]->[Float]
divi a xs = [x-a | x <- xs]

xx::Float->[Float]->[Float]
xx a xs = [x/a|x<-xs]

i can not figure out what's wrong with this program. is shows an error like this

ERROR file:.\SD.hs:11 - Type error in application
*** Expression     : read (length m)
*** Term           : length m
*** Type           : Int

can you guys please point me out problem in this program, thank you * Does not match : [Char]

Upvotes: 0

Views: 165

Answers (2)

wvoq
wvoq

Reputation: 573

There are a few things going on in your code that you might want take a look at. You have:

let stdd = xx length(m-1) m

which will not typecheck. I think you meant:

let stdd = xx (length m-1) m

(Edit: actually, that won't check either due to the type signature for xx. (Why not?)) This line:

let mean = (fromIntegral x)/(fromIntegral $ length )

is a Num divided by a function.

In this line:`

 let std = map (^2) divia

what is the type of divia, and what is the type of (^2)?

Finally, what actually happens in the case of the empty list, or even a singleton list?

As an aside, you might want to consider which parts of your program really need to live inside main. As it stands, you're

  • Printing a line
  • Reading input
  • Computing the standard deviation
  • Printing the result of that computation

Why not factor out a standardDev function? That might make your main function shorter and clearer. Writing pure functions also allows you to test your functions in the REPL more conveniently. When I code, I find it very helpful to build short, obviously correct functions, compose them in order to obtain tge desired behavior, and dump the result into the IO monad only at the very last moment.

Upvotes: 1

rochem
rochem

Reputation: 313

The function read has type String -> 'a ; your error tells you that length m has type Int, while read is waiting for a String. You might want to use genericLength from Data.List:

    let len = Data.List.genericLength m :: Float

Upvotes: 0

Related Questions