[Haskell-beginners] Reading input
cmb21 at kent.ac.uk
Wed Aug 20 16:25:41 EDT 2008
You can use read:
lst <- getline
median (read lst::[Int])
You will have to enter your list like this at the prompt:
read transforms Strings into some other type (usually specified by a type
read :: Read a => String -> a
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
> 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?
> Beginners mailing list
> Beginners at haskell.org
More information about the Beginners