0

So my problem is to take a string in haskell and to modify it so that if there are certain characters, they are changed to other characters, and I have created a helper function to do this, however there is one case where if the character is '!' then it become '!!!111oneone', so i figure to do this you would need to concatenate the current string with '!!111oneone', the trouble is that my function was working with chars however to do this we would need to work with the string, how would you combine this, ie a helper to modify the chars if necessary and implementing the conversion if there is a '!'.

Here is what i have so far

convert :: String -> String
convert [] = []
convert (x:xs) =
| x == '!'  = !helper
| otherwise = converthelper x
2
  • You can use ++ to concatenate strings. If c is a single char, you can use [c] to turn it into a string (if you need to). Instead c : s prepends char c to the string s. Commented Mar 25, 2019 at 19:15
  • ok thanks ill try to implement that! Commented Mar 25, 2019 at 19:19

1 Answer 1

3

Assuming your helper is something like

helper :: Char -> String
helper '!' = "!!!111oneone"
helper c = [c]

then you can use concatMap to map helper over each character in your string, and then concatenate the results into a single string.

convert :: String -> String
convert = concatMap helper
-- convert msg = concatMap helper msg

The trick is that your helper promotes every character to a list of characters; most characters just become the corresponding one-character string, but ! becomes something more.

(Note that concatMap forms the basis of the Monad instance for lists. You could also write convert msg = msg >>= helper.)

Sign up to request clarification or add additional context in comments.

6 Comments

Congrats, you've just defined an L-System. (Ok, technically you also need a starting string.)
Heh, I don't think I ever knew there was a formal name for that process.
(Of course, in this case we're stopping after one round of replacements.)
This is a very nice approach, but I fear it is too high-level for the OP who is a beginner and did not know about ++, which is more basic than concatMap.
Yep. iterate (>>= helper) will give you the whole sequence.
|

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.