Jake
Jake

Reputation: 610

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 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

Upvotes: 3

Views: 398

Answers (3)

rampion
rampion

Reputation: 89053

uncurry replicate

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

Upvotes: 9

hugomg
hugomg

Reputation: 69934

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.

Upvotes: 8

Ramon Snir
Ramon Snir

Reputation: 7560

You want replicate.

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

Upvotes: 6

Related Questions