我写了下面的代码:
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"
在 no.txt 中:
one
two
three
four
....
编译运行代码后,得到结果:
1
但我希望得到:
1
2
3
4
...
代码有什么问题?有什么帮助吗?谢谢!
最佳答案
从 readFile
读取时,
str
不是字符串列表(它只是一个类似于 one\ntwo
的字符串)。做
main = do
str <- readFile "no.txt"
mapM_ (\x -> putStrLn (show(english x))) $ lines str
在您的 main
中使用 lines
将 str
转换为列表(参见 lines 的文档)。
关于Haskell - 打印数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7813120/