[Haskell-beginners] Reading input

Yitzchak Gale gale at sefer.org
Wed Aug 20 16:31:16 EDT 2008


Hi Barry,

Barry Burd wrote:
> median :: [Int] -> Int
> median lst =
>  case medians lst of
>    -- All the values in the result are the same, we just pick the first one
>    x:xs -> x
>
> main = do
>    putStr "Enter a list: "
>    lst <- getLine
>    median lst

> I'm sure this is because Haskell isn't automatically changing a String
> to a List of numbers. But how can I do this?

Use the "read" function. Watch out, though - there is
no error checking there. So if the user enters a string
that does not have the right syntax for a Haskell list
of integers, your program will halt with an error message.

You have another problem - you used the "median"
function as a step in a do block - but each step in a
do block must have type "IO a" for some type a.

Here's how you could write your main function:

main = do
   putStr "Enter a list: "
   lst <- getLine
   print $ median $ read lst

Regards,
Yitz


More information about the Beginners mailing list