Haskfan
Haskfan

Reputation: 35

How can I add n whitespaces after a string with recursion in Haskell?

For example a number (5) and a string (apple) is given, and the program drops (apple_____). I want to do this with recursion. I tried this way:

add :: Integer -> [Char] -> [Char]
add 0 (x:xs) = (x:xs)
add i [] = add (i-1) [] ++ " "
add i (x:xs) = format (i-1) xs

Upvotes: 1

Views: 344

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476709

Given you want to add 0 spaces, you can return the given string (1); if the string is non-empty, you emit the first element of the string x and recurse on the tail of the string (2); finally if we reached the end of the string, and i is greater than 0, we emit a space, and recurse with i one less than the given i (3):

add :: Integer -> String -> String
add i xs | i <= 0 = xs  -- (1)
add i (x:xs) = x : …    -- (2)
add i [] = ' ' : …      -- (3)

You here still need to fill in the parts.

Upvotes: 2

Related Questions