0

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!

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

[ a | a <- [list], _ <- [1..num]] can be rewritten as [ list | _ <- [1..num]]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.