[Haskell-beginners] Reading input

C.M.Brown cmb21 at kent.ac.uk
Wed Aug 20 16:25:41 EDT 2008


Hi Barry,

You can use read:

...
lst <- getline
median (read lst::[Int])
...


You will have to enter your list like this at the prompt:

> [1,2,3,4]

read transforms Strings into some other type (usually specified by a type
annotation).

read :: Read a => String -> a


HTH
Chris.




On Wed, 20 Aug 2008, Barry Burd wrote:

> In the last line of this program, I get the following error message (from ghci)...
>
>     Couldn't match expected type `Int' against inferred type `Char'
>       Expected type: [Int]
>       Inferred type: String
>     In the first argument of `median', namely `lst'
>     In the expression: median lst
> Failed, modules loaded: none.
>
> Here's the program...
>
> module Main
>     where
>
> import IO
>
> lessThan :: Int -> [Int] -> [Int]
> lessThan x lst = filter (< x) lst
>
> greaterThan :: Int -> [Int] -> [Int]
> greaterThan x lst = filter (> x) lst
>
> numLessThan :: Int -> [Int] -> Int
> numLessThan x lst = length (lessThan x lst)
> numGreaterThan :: Int -> [Int] -> Int
> numGreaterThan x lst = length (greaterThan x lst)
>
> numLessGreater :: Int -> [Int] -> (Int, Int)
> numLessGreater x lst = (numLessThan x lst, numGreaterThan x lst)
>
> isMedian :: (Int, Int) -> Bool
> isMedian (x, y) = x == y
>
> medians :: [Int] -> [Int]
> medians lst = [x | x <- lst, isMedian (numLessGreater x lst)]
>
> 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?
> Thanks.
>
> _______________________________________________
> Beginners mailing list
> Beginners at haskell.org
> http://www.haskell.org/mailman/listinfo/beginners
>


More information about the Beginners mailing list