[英]Multiplying String in a list, Haskell
I am trying to multiply strings in a list. 我正在尝试将列表中的字符串相乘。 For instance, when I have a list like
["hello","World"]
and I want to 'multiply' it by 2, I want to end up with ["hello","hello","World","World"]
. 例如,当我有一个类似
["hello","World"]
的列表["hello","World"]
并且想要将它“乘以2”时,我想以["hello","hello","World","World"]
结尾["hello","hello","World","World"]
。
Here's what I came up with: 这是我想出的:
rep :: Int -> [String] -> [String]
rep n [] = []
rep n [x:xs] = replicate n [x] ++ rep n [xs]
But it gives me exception: 但这给了我例外:
(298,1)-(299,44): Non-exhaustive patterns in function rep
(298,1)-(299,44):函数rep中的非穷举模式
I am totally new to this language and I do not have any ideas how to sort this out. 我是这种语言的新手,我不知道如何进行整理。 Can you help?
你能帮我吗?
(x:xs)
, not [x:xs]
. (x:xs)
,而不是[x:xs]
。 n
, so it should be replicate nx
, not replicate n [x]
. n
的列表,因此应replicate nx
,而不replicate n [x]
。 xs
is already a list. xs
已经是一个列表。 If you fix all of this you'll end up with the following, which actually works as intended: 如果解决了所有这些问题,将得到以下结果,这些结果实际上可以按预期工作:
rep :: Int -> [String] -> [String]
rep n [] = []
rep n (x:xs) = replicate n x ++ rep n xs
That said there are many different ways one could write this, for example with concatMap : 也就是说,可以使用多种不同的方式编写此代码,例如使用concatMap :
rep n = concatMap (replicate n)
or 要么
rep = concatMap . replicate
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.