从 IO ExitCode monad 获取字符串

发布于 2024-12-16 13:40:58 字数 371 浏览 5 评论 0原文

我试图将作为参数给出的字符串(使用 getArgs )连接到 haskell 程序,例如: "rm " ++ filename ++ " filename2.txt" 位于 main = do 块内。

问题出在文件名的类型上,ghc 不会编译它,并给出错误。

我收到错误 无法将预期类型 [a] 与推断类型 IO ExitCode 匹配

我们尝试运行的代码是:

args <- getArgs
let inputfname = head args
system "rm -f "++ inputfname ++ " functions.txt"

I'm trying to concatenate a string given as an argument (using getArgs) to the haskell program, e.g.:
"rm " ++ filename ++ " filename2.txt" which is inside a main = do block.

The problem is with the type of filename, and ghc won't compile it, giving an error.

I get an error Couldn't match expected type [a] against inferred type IO ExitCode

the code we're trying to run is:

args <- getArgs
let inputfname = head args
system "rm -f "++ inputfname ++ " functions.txt"

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

老娘不死你永远是小三 2024-12-23 13:40:58

您需要 $

system $ "rm -f "++ inputfname ++ " functions.txt"

或括号:

system ("rm -f " ++ inputfname ++ " functions.txt")

否则您将尝试运行此:

(system "rm -f ") ++ inputfname ++ " functions.txt"

它会失败,因为 ++ 想要 [a] (在本例中String),但获取IO ExitCode(来自system)。

You need $:

system $ "rm -f "++ inputfname ++ " functions.txt"

Or parentheses:

system ("rm -f " ++ inputfname ++ " functions.txt")

Otherwise you’re trying to run this:

(system "rm -f ") ++ inputfname ++ " functions.txt"

It fails because ++ wants [a] (in this case String) but gets IO ExitCode (from system).

爱,才寂寞 2024-12-23 13:40:58

问题是函数应用程序的优先级高于 (++) 运算符,因此它会解析为

(system "rm -f ") ++ inputfname ++ " functions.txt"

您的意思是

system ("rm -f " ++ inputfname ++ " functions.txt")

或只是

system $ "rm -f " ++ inputfname ++ " functions.txt"

The problem is that function application has higher precedence than the (++) operator, so it parses as

(system "rm -f ") ++ inputfname ++ " functions.txt"

while what you meant was

system ("rm -f " ++ inputfname ++ " functions.txt")

or simply

system $ "rm -f " ++ inputfname ++ " functions.txt"
雄赳赳气昂昂 2024-12-23 13:40:58

以下代码有效:

import System.Process
import System.Environment

main = do
   args <- getArgs
   let inputfname = head args
   system $ "rm -f "++ inputfname ++ " functions.txt"

其他评论者解释了原因。

The following code works:

import System.Process
import System.Environment

main = do
   args <- getArgs
   let inputfname = head args
   system $ "rm -f "++ inputfname ++ " functions.txt"

The reasons were explained by other commenters.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文