23

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

      a <- (entryGetText text_field)

The goal is to combine it like:

newstring = "Text: "+a

Any ideas to accomplish that? Thanks!

1
  • 2
    newstring <- fmap ("Text: " ++) $ entryGetText text_field Commented May 25, 2012 at 14:15

3 Answers 3

32

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)
Sign up to request clarification or add additional context in comments.

1 Comment

To expand on that last line of code: <$> is equivalent to `fmap` as infix operator. So what this does is that it takes the value out of the IO Monad (entryGetText text_field) and applies ("Text:" ++) to it.
15

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

2 Comments

No! That is concatenation of lists.
@Lindhea The String type is just a List of Chars, so ++ will also work on Strings. For example, "has" ++ "kell" returns "haskell".
6

The very moment you use the assignment operator x <- expr with expr :: m a and m being some monad, x is not an m a but rather an a. In your case, the variable a has type String and not IO String, so you can concatenate it as you would do in pure code, e.g. "hello world " ++ a.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.