有没有一种方法可以在没有辅助函数的情况下轻松构建 Haskell 中的重复元素列表?

发布于 2024-12-09 03:27:31 字数 498 浏览 7 评论 0原文

给定一个 (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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

不知在何时 2024-12-16 03:27:31

咖喱复制

Prelude> :t uncurry replicate
uncurry replicate :: (Int, b) -> [b]
Prelude> uncurry replicate (4, 'b')
"bbbb"

uncurry replicate

Prelude> :t uncurry replicate
uncurry replicate :: (Int, b) -> [b]
Prelude> uncurry replicate (4, 'b')
"bbbb"
ㄟ。诗瑗 2024-12-16 03:27:31

有一个内置的复制为此。

查看 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.

清醇 2024-12-16 03:27:31

您想要复制

找到这些东西的好方法:
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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文