【问题标题】:HASKELL *** Exception: Prelude.read: no parse (possible duplicate)HASKELL *** 例外:Prelude.read:无解析(可能重复)
【发布时间】:2021-12-21 12:10:59
【问题描述】:

我有这个代码

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 []

当我尝试运行它时,它给了我这个错误:

[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>

我看过类似的问题,我知道该错误与我对read 的使用有关,但我不了解更多。我在这里做错了什么?

【问题讨论】:

  • 使用read (..) :: Char,您正在尝试解析Char,并且字符应该用单引号括起来,例如'a''1'。但是您的输入没有任何引号。
  • 非常感谢!

标签: parsing haskell parse-error


【解决方案1】:

head ord 只是"1"。要使 read 将其变为 Char,则必须改为 "'1'"。由于String 只是[Char],因此您可以只使用第一个元素来获得您想要的东西,而不用在read 那里烦恼。

【讨论】:

    猜你喜欢
    • 2017-01-18
    • 1970-01-01
    • 2018-08-28
    • 1970-01-01
    • 1970-01-01
    • 2018-02-11
    • 2023-03-19
    • 2013-03-21
    • 1970-01-01
    相关资源
    最近更新 更多