I need to write a haskell function that duplicates each occurrence of a character in a string specified by the user.

So far this is what I have. I know that this has something to do with the function itself, since I have Char → String → String, but I need it to be entered by the user, so IO. I am not sure how to do this.

dup :: Char -> String -> String
dup c [] = []
dup c (x:xs)
  | c == x    =  x:x:dup c xs
  | otherwise =  x:dup c xs

main = do
  putStrLn "Enter a sentence."
  sentence <- getLine
  putStrLn "Enter a single letter that is in your sentence, to duplicate."
  letter <- getLine
  let x = dup 'letter''sentence'
   putStrLn x
+4
source share
2 answers

There are several problems, so I will be fine. First, the syntax is:

  • You do not want the latter to putStrLn xbe at a different level of indentation from the rest of your block do.
  • You do not want to surround letterwith sentencesingle quotes in the function call.

, :

• '[ Char] ' Char       : Char         :     • "dup", "letter"        : dup letter sentence        "x: x = dup letter

, letter String, Char. getChar, IO Char, IO String:

main = do
  putStrLn "Enter a sentence."
  sentence <- getLine
  putStrLn "Enter a single letter that is in your sentence, to duplicate."
  letter <- getChar
  let x = dup letter sentence
  putStrLn $ '\n' : x

'\n' x, .

:

ghci>> main
Enter a sentence.
hi
Enter a single letter that is in your sentence, to duplicate.
h
hhi
+2

. getLine String [Char], Char. :

main = do
  putStrLn "Enter a sentence."
  sentence <- getLine
  putStrLn "Enter a single letter that is in your sentence, to duplicate."
  -- Get first character only
  letter:_ <- getLine
  let x = dup letter sentence
  putStrLn x

, , , , .

+3

Source: https://habr.com/ru/post/1663185/


All Articles