gpt4 book ai didi

Haskell - 打印数字

转载 作者:行者123 更新时间:2023-12-04 20:51:37 26 4
gpt4 key购买 nike

我写了下面的代码:

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 中使用 linesstr 转换为列表(参见 lines 的文档)。

关于Haskell - 打印数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7813120/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com