到目前为止,这就是我所拥有的。我知道它与函数本身有关,因为我有Char - >字符串 - >字符串,但我需要它从用户输入,所以IO。我不确定该怎么做。
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
答案 0 :(得分:3)
如此接近。如果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
对此有一些警告,因为模式匹配可能会失败,但它会起作用,并且它与你所写的非常接近。
答案 1 :(得分:2)
有一些问题,所以我会按顺序排列。首先,语法:
putStrLn x
与do
块的其他内容处于不同的缩进级别。letter
和sentence
。如果我们更改这些并尝试编译,我们会收到以下错误:
•无法将类型'[Char]'与'Char'匹配 预期类型:Char 实际类型:字符串 •在'dup'的第一个参数中,即'letter' 在表达式中:dup letter的句子 在'x'的等式中:x =重复字母句子
问题是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