Recurion is not terminated

Viewed 61

I have a following problem. My aim is to implement function that returns Char the n number of times

GHCi> nTimes 42 3
[42,42,42]
GHCi> nTimes 'z' 5
"zzzzz"

I have implemented such solution but recursion does not end

nTimes:: a -> Int -> [a]
nTimes a n = a : nTimes a (n-1)

And function just returs an unstoppable number Chars Thanks in advance,

1 Answers

In order to stop a recursion, you need a base case. A case that will not make recursive calls again. Your nTimes however does not have a base case. Why would nTimes 'z' 0 be treated special? According to your program that is just a case like any other. It will prepend a to list, and make a recursive call with nTimes a (-1).

You thus can implement a base case, for example with a guard:

nTimes:: a -> Int -> [a]
nTimes a n
    | n <= 0 = []
    | otherwise = a : nTimes a (n-1)

So if n is less than or equal to 0, we return an empty list. In the otherwise case (n > 0), we thus yield a and then recurse with nTimes a (n-1).

If we test this with nTimes 'z' 5 we get:

Prelude> nTimes 'z' 5
"zzzzz"

You here implemented a "flipped" version of the replicate :: Int -> a -> [a] function, so you can simply write this as nTimes = flip replicate.

Related