gpt-4-1106-preview· openai
Suzhen/CodeChat
Haskell中,如何获得将一个字符串重复多次后得到的字符串?
- User
Haskell中,如何获得将一个字符串重复多次后得到的字符串?
- Assistant
在Haskell中,你可以使用
replicate函数来获得将字符串重复多次后得到的字符串。replicate函数接受两个参数,第一个参数是重复的次数,第二个参数是要重复的值。这里有个简单的例子,展示了如何将字符串
"hello"重复3次得到"hellohellohello":haskellrepeatedString :: Int -> String -> String repeatedString n str = concat (replicate n str) main :: IO () main = putStrLn (repeatedString 3 "hello")上面的代码中,
replicate会创建一个由3个"hello"组成的列表["hello", "hello", "hello"],然后concat函数将这个列表中的所有字符串连接成一个字符串。如果你只需要简单地重复字符串,甚至不需要定义一个单独的函数,你可以在
ghci里面或者直接在你的代码中这样写:haskellmain :: IO () main = putStrLn (concat (replicate 3 "hello"))或者更简洁地,使用列表解析(list comprehension)来达到相同的效果:
haskellmain :: IO () main = putStrLn (concat [ "hello" | _ <- [1..3] ])在这个例子里,列表解析为1到3的每个元素(在这里是占位符
_,因为我们不关心具体的值)创建了"hello"的一个实例,然后concat将它们连接起来。