user3410327
user3410327

Reputation: 79

Haskell doubling characters in a string

I have basically been asked to turn "HelloWorld!" to "HheellllooWwoorrlldd!!" with a Haskell function using only this type

stringDub :: String -> String

I am not looking for a straight answer, just some pointers on how to go about doing that as I am completely new to Haskell.

Thanks in advance.

Upvotes: 2

Views: 639

Answers (2)

andrasbelo
andrasbelo

Reputation: 11

Or since Strings are Lists, and Lists are monads:

stringDub' :: String -> String
stringDub' xs  = do
  xs >>= \x -> [x,x]

Upvotes: 1

Mark H
Mark H

Reputation: 13907

You use pattern matching to break the argument into the first character and remaining characters, then recursively call the stringDub function on the tail. You also need to check for the empty list in order to end the recursion when there are no more elements.

stringDub []    = []
stringDub (h:t) = doubleItUp h ++ stringDub t
  where doubleItUp :: Char -> String
        doubleItUp = -- fill in the rest.

Upvotes: 2

Related Questions