gpt4 book ai didi

function - 我需要编写一个haskell 函数来复制字符串中出现的每个字符,两者都是由用户给出的。

转载 作者:行者123 更新时间:2023-12-05 00:53:35 24 4
gpt4 key购买 nike

到目前为止,这就是我所拥有的。我知道它与函数本身有关,因为我有 Char -> String -> String,但我需要用户输入它,所以 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

最佳答案

很近。哪里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

对此有一些警告,因为模式匹配可能会失败,但它会起作用,并且与您编写的内容非常接近。

关于function - 我需要编写一个haskell 函数来复制字符串中出现的每个字符,两者都是由用户给出的。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41030541/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com