string 如何在 Haskell 中连接两个(IO)字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10755852/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 01:29:01  来源:igfitidea点击:

How to concat two (IO) Strings in Haskell?

stringhaskellconcat

提问by user1415426

I know this sound very simple, but I failed to combine two strings into a new one.

我知道这听起来很简单,但我没能将两个字符串组合成一个新的字符串。

The IO String "a" from a gtk entry is fetched by

来自 gtk 条目的 IO 字符串“a”由

      a <- (entryGetText text_field)

The goal is to combine it like:

目标是将它组合起来,如:

newstring = "Text: "+a

newstring = "文本:"+a

Any ideas to accomplish that? Thanks!

有什么想法可以实现吗?谢谢!

回答by Don Stewart

Using string concatenation:

使用字符串连接:

 do a <- entryGetText text_field
    let b = "Text:" ++ a
    return b

More simply:

更简单:

 do a <- entryGetText text_field
    return $ "Text:" ++ a

You can play games too:

你也可以玩游戏:

 ("Text:" ++) <$> (entryGetText text_field)

回答by Puppy

I believe that in Haskell, the string concatenation operator is ++.

我相信在 Haskell 中,字符串连接运算符是++.

回答by Riccardo T.

The very moment you use the assignment operator x <- exprwith expr :: m aand mbeing some monad, xis not an m abut rather an a. In your case, the variable ahas type Stringand not IO String, so you can concatenate it as you would do in pure code, e.g. "hello world " ++ a.

非常时刻,你使用赋值操作符x <- exprexpr :: m am为一些单子,x不是一个m a,而是一个a。在您的情况下,变量a具有 typeString而不是IO String,因此您可以像在纯代码中一样连接它,例如"hello world " ++ a.