开发者

Is there a way for easy construction of a list of repeated elements in Haskell without helper functions?

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 f开发者_Python百科ollowing:

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


uncurry replicate

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


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.


You want replicate.

A good way to find those things: http://haskell.org/hoogle/?hoogle=Int+-%3E+a+-%3E+%5Ba%5D

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜