So I’ve been enjoying this challenging language, I am currently working on an assignment for school.
This is what it says: I need to prompt the user for a list of numbers, then display the average of the list , I am so close to figuring it out. However I get this weird parse error:
"Exception: user error (Prelude.readIO: no parse)"
Here is my code:
module Main (listM', diginums', getList, main) where
import System.IO
import Data.List
diginums' = []
listM' = [1, 2, 3]
average' = (sum diginums') / (fromIntegral (length diginums'))
getList :: IO [Double]
getList = readLn
main = do
putStrLn "Please enter a few numbers"
diginums' <- getList
putStrLn $ show average'
Terminal Prompts : Enter a few #'s
I Enter : 123
ERROR : Exception: user error (Prelude.readIO: no parse)
I know my functions are working correctly to calculate the average. Now I think my problem is that when I take in the list of numbers from the user, I don’t correctly parse them to type Double for my average function.
Your type signature says that
reads a list of
Doubles, that means it expects input of the formbut you gave it what could be read as a single number,
"123". Thus thereadfails, the input couldn’t be parsed as a[Double].If you want to parse input in a different form, not as syntactically correct Haskell values, for example as a space-separated list of numbers, you can’t use
readLn, but have to write a parser for the desired format yourself. For the mentioned space-separated list of numbers, that is very easy, e.gIf you want to get the list in the form of numbers each on its own line, ended by an empty line, you’d use a recursion with an accumulator,
Parsers for more complicated or less rigid formats would be harder to write.
When the parsing is fixed, you run into the problem that you haven’t yet got used to the fact that values are immutable.
defines three values, the
Doublevalueaverage'is defined in terms of the empty listdiginums', hence its value iswhich is a
NaN.What you need is a function that computes the average of a list of
Doubles, and apply that to the entered list inmain.