我有這個代碼
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,但我不明白更多。我在這里做錯了什么?
uj5u.com熱心網友回復:
head ord只是"1". 為了read使它成為 a Char,它必須是"'1'"。由于 aString只是 a [Char],您可以只使用第一個元素來獲得您想要的東西,而不用在read那里費心。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/354810.html
