[Haskell-beginners] Reading input
Barry Burd
bburd at drew.edu
Wed Aug 20 16:19:36 EDT 2008
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.
More information about the Beginners
mailing list