有没有一种方法可以在没有辅助函数的情况下轻松构建 Haskell 中的重复元素列表?
给定一个 (Int, a)
类型的元组,例如 (n,c)
,我希望构造一个列表 [a]
,其中元素c
重复n
次,即(4, 'b')
变为"bbbb"
。我当前的解决方案如下:
decode :: (Int, a) -> [a]
decode (n, a) = map (\x -> a) [1..n]
如您所见,我正在映射一个匿名函数,该函数始终在 n
元素(前 n 个正整数)列表上返回 a
。有没有更有效的方法来做到这一点?我对构造一个整数列表却从不使用它感到难过。另一种解决方案是使用辅助函数并向下递归n
,但这看起来很混乱且过于复杂。是否有类似于以下 python 代码的内容?
'b'*4
Given a tuple of type (Int, a)
such as (n,c)
, I wish to construct a list [a]
where the element c
is repeated n
times, i.e., (4, 'b')
becomes "bbbb"
. My current solution is the following:
decode :: (Int, a) -> [a]
decode (n, a) = map (\x -> a) [1..n]
As you can see, I'm mapping an anonymous function that always returns a
over a list of n
elements, the first n positive integers. Is there a more efficient way to do this? I feel bad about constructing a list of integers and never using it. Another solution would use a helper function and recurse down n
, but that seems messy and overcomplicated. Is there perhaps something akin to the following python code?
'b'*4
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
咖喱复制
uncurry replicate
有一个内置的复制为此。
查看 Hoogle当您需要查找是否已经有一个函数可以在某处执行您想要的操作时。
There is a builtin replicate for that.
Check out Hoogle for when you need to find if there is already a function that does what you want somewhere.
您想要
复制
。找到这些东西的好方法:
http://haskell.org/hoogle/?hoogle =Int+-%3E+a+-%3E+%5Ba%5D
You want
replicate
.A good way to find those things:
http://haskell.org/hoogle/?hoogle=Int+-%3E+a+-%3E+%5Ba%5D