Question

have to write functions with the same effekt like the replicate-function.

  1. List comprehension:

My try:

rep list = [ a | a <- list, _ <- [1..a]]

Works great with Ints, but I want to use this with chars too. Something like this:

rep 4 "Hello"   => "Hello", "Hello", "Hello", "Hello"

2 Recursion:

rep :: (Num i, Ord i) => i -> a -> [a]  
rep n x  
    | n <= 0    = []  
    | otherwise = x:rep (n-1) x  

Same Problems with chars!

Was it helpful?

Solution

For list comprehension, this should work:

rep :: (Enum a, Num a) => a -> t -> [t]
rep num list = [ a | a <- [list], _ <- [1..num]]

Or in a more efficient and nice form (Thanks to @chi):

rep num list = [ list | _ <- [1..num]]

Demo:

λ> rep 3 3
[3,3,3]
λ> rep 3 "hello"
["hello","hello","hello"]

Your recursive program works fine for me in both cases.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top