我写了以下代码:
module Test where
import Char
import IO
main = do
str <- readFile "no.txt"
putStrLn (show(english str))
string2list :: String -> [String]
string2list "" = []
string2list s = words s
english :: String -> Int
english s
| head (string2list s) == "one" = 1
| head (string2list s) == "two" = 2
| head (string2list s) == "three" = 3
| head (string2list s) == "four" = 4
| head (string2list s) == "five" = 5
| head (string2list s) == "six" = 6
| head (string2list s) == "seven" = 7
| head (string2list s) == "eight" = 8
| head (string2list s) == "nine" = 9
| otherwise = error "not match"
Run Code Online (Sandbox Code Playgroud)
在no.txt中:
one
two
three
four
....
Run Code Online (Sandbox Code Playgroud)
在编译并运行代码之后,我得到了结果:
1
Run Code Online (Sandbox Code Playgroud)
但我希望得到:
1
2
3
4
...
Run Code Online (Sandbox Code Playgroud)
代码有什么问题?有帮助吗?谢谢!
strone\ntwo读取时不是字符串列表(它只是一个字符串)readFile.做
main = do
str <- readFile "no.txt"
mapM_ (\x -> putStrLn (show(english x))) $ lines str
Run Code Online (Sandbox Code Playgroud)
在你的main代替和使用转换str为列表lines(见文档的行).
这不是你的问题的答案,而是风格的建议.你可以摆脱那些罗嗦head (string2list s)使用模式匹配和替换的东西string2list用words; 两者都完全相同:
english s = case words s of
"one" :_ -> 1
"two" :_ -> 2
"three" :_ -> 3
"four" :_ -> 4
"five" :_ -> 5
"six" :_ -> 6
"seven" :_ -> 7
"eight" :_ -> 8
"nine" :_ -> 9
_ -> error "no match"
Run Code Online (Sandbox Code Playgroud)