Home > OS >  HASKELL *** Exception: Prelude.read: no parse (possible duplicate)
HASKELL *** Exception: Prelude.read: no parse (possible duplicate)

Time:11-09

I have this code

import Data.Char (isDigit)

eval :: [Int] -> IO()
eval liste = do
    putStrLn "Please enter a positive integer or an operater (   / - / * ): "
    input <- getLine
    let
        ord = words input
        cmd = read (head ord) :: Char
        in
            if isDigit cmd then
                let nyliste = (read [cmd] :: Int) : liste in do
                print nyliste
                eval nyliste
            else if isOperator cmd then if null liste || length liste == 1 then do
                    putStrLn "Invalid input! Start by adding at least two positive integers"
                    eval liste
                else let
                    fst = head liste
                    snd = head $ tail liste
                    in case cmd of
                        ' ' -> let
                            newValue = fst   snd
                            oppliste = newValue : drop 2 liste
                            in do
                                print oppliste
                                eval oppliste
                        '-' -> let
                            newValue = fst - snd
                            oppliste = newValue : drop 2 liste
                            in do
                                print oppliste
                                eval oppliste
                        '*' -> let
                            newValue = fst * snd
                            oppliste = newValue : drop 2 liste
                            in do
                                print oppliste
                                eval oppliste
                        _ -> do
                            putStrLn "Invalid input! Start by adding at least two positive integers"
                            eval liste
            else do
                putStrLn "Invalid input! Start by adding at least two positive integers"
                eval liste


isOperator :: Char -> Bool
isOperator c = c == '*' || c == ' ' || c == '-'

main :: IO()
main = eval []

Which, when I try to run it, it gives me this error:

[1 of 1] Compiling Main             ( test.hs, interpreted )
Ok, one module loaded.
ghci> main
Please enter a positive integer or an operater (   / - / * ):
1
*** Exception: Prelude.read: no parse
ghci>

I have looked at similar questions, and I understand that the error has something to do with my use of read, but I don't understand much more than that. What am I doing wrong here?

CodePudding user response:

head ord is just "1". For read to make that into a Char, it would have to be "'1'" instead. Since a String is just a [Char], you can just take the first element to get what you want instead of bothering with read there at all.

  • Related