在列表中将字符串乘以Haskell [英] Multiplying String in a list, Haskell

查看:89
本文介绍了在列表中将字符串乘以Haskell的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在列表中乘以字符串。例如,当我有一个像 [hello,World] 这样的列表,并且我想将它乘以2时,我希望以 [hello,hello,World,World]

下面是我想到的:

  rep :: Int  - > [字符串]  - > [String] 
rep n [] = []
rep n [x:xs] = replicate n [x] ++ rep n [xs]

但它给了我例外:


(298,1) - (299,44):函数rep中的非穷举模式

我对这种语言完全陌生,我没有想法如何解决这个问题。你可以帮忙吗?

解决方案


  • 你的第一个问题是非空列表的模式是错误的,它应该是(x:xs),而不是 [x:xs]

  • 此外,复制期待一个单一元素并将其转换为长度 n 的列表,所以它应该是 replicate nx ,而不是 replicate n [x]

  • 类似的徒劳的 xs 已经是一个列表。



如果您解决了所有这些问题,您最终会得到以下结果,这些结果实际上按预期运行:

  rep :: Int  - > [字符串]  - > [String] 
rep n [] = []
rep n(x:xs)= replicate nx ++ rep n xs

也就是说有很多不同的方法可以编写它,例如 concatMap

  rep n = concatMap(replicate n)

  rep = concatMap。复制


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"].

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

I am totally new to this language and I do not have any ideas how to sort this out. Can you help?

解决方案

  • Your fist problem is that the pattern for non-empty lists is wrong, it should be (x:xs), not [x:xs].
  • Furthermore, replicate expects a single element and turns it into a list of length n, so it should be replicate n x, not replicate n [x].
  • In a similar vain xs is already a list.

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:

rep n = concatMap (replicate n)

or

rep = concatMap . replicate

这篇关于在列表中将字符串乘以Haskell的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆