首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >HASKELL *异常: Prelude.read:无解析(可能重复)

HASKELL *异常: Prelude.read:无解析(可能重复)
EN

Stack Overflow用户
提问于 2021-11-08 16:53:38
回答 1查看 56关注 0票数 1

我有这个代码

代码语言:javascript
运行
复制
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 []

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

代码语言:javascript
运行
复制
[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的使用有关,但除此之外,我并不了解更多。我在这里做错了什么?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-11-08 17:05:17

head ord就是"1"。对于read来说,它必须是Char,而不是"'1'"。因为String只是一个[Char],所以您可以只取第一个元素来获得您想要的东西,而不需要在那里费心使用read

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69887108

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档