Reputation: 11
I am quite a beginner and I am trying to write a function in Haskell that would take in a number n and a given string. The function will then return the string with n spaces between each letter in the string. For example the function addSpace 2 "hello" will return the following "h e l l o".
For the moment I have only managed to have a function that would take in a String and just add a single space between each letter.
addSpace :: String -> String
addSpace s = if length s <= 1
then s
else take 1 s ++ " " ++ addSpace (drop 1 s)
However the function in Haskell I would like it to be:
addSpace :: Integer -> String -> String
Appreciate all help!
Upvotes: 1
Views: 397
Reputation: 71495
You already have a working implementation that adds a string between every character of the input string; it's just that the string to be added is hardcoded as " "
. So it should be fairly obvious that all you need to do is replace the " "
with some function call that takes an Integer
and works out how many spaces there should be:
addSpace :: Integer -> String -> String
addSpace n s
= if length s <= 1
then s
else take 1 s ++ makeSpaces n ++ addSpace (drop 1 s)
Now all you have to do is define the makeSpaces
function. From how we're using it, it must have this type:
makeSpaces :: Integer -> String
makeSpaces n = _
I'm not going to give you any more code, but you can implement it very similarly to the recursion scheme you already demonstrated in addSpace
, only instead of the choice of whether to recurse of not being based on the length of an input string, it will be based on the value of an input integer. When n
is zero, what should you return? When it's greater than zero, what should you add to a recursive call to get the right answer? And how should you transform n
as input for the recursive call.
For bonus points1: your current addString
works (at least for finite inputs) but can be very inefficient, because every time you ask for the length
of a string (which you do in every recursive call) it has to walk the entire string to count out the length. Since you don't actually use the length for anything except checking whether it it's less than or equal to 1, do you really need to calculate the exact length? If you've been shown pattern matching2 then you should be able to think of a way to tell whether a list has at least one character in it without calling length
.
1 I say "bonus points" because an addSpace :: Integer -> String -> String
function based on the way you've written your current solution works and I imagine it would get a decent mark in a beginner course, but I also imagine it will not get a top mark; the code is inefficient and longer than it needs to be.
2 If you haven't been shown pattern matching then (a) you can ignore this whole "bonus points" paragraph, as I don't think it will be required of you to get a good mark, and (b) they're teaching you Haskell in a very weird order.
Upvotes: 1