Rob Ants
Rob Ants

Reputation: 29

Haskell: How to carry a value from one function to another

I have a function 'one' that creates a string of length i,

fillWithEmpty :: Int -> String
fillWithEmpty i =
  if i == 0 then "." else "." ++ fillWithEmpty(i - 1)

I then want the system to remember the length i so that it can replace a character in the string with 'S' at a position in the string of length i, given a value of a position needed to be replaced, e

replaceWithS :: String -> Int -> String
replaceWithS i e=
  if i == e then "S" else "." ++ replaceWithS(i - 1)

Any help would be appreciated. Thanks

Upvotes: 1

Views: 173

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477240

You can use explicit recursion to enumerate over the list. Each time you make a call where you decrement the index, and if the index is 0 you use an S instead of the value of the given string, so:

replaceWithS :: String -> Int -> String
replaceWithS "" _ = ""
replaceWithS (_:xs) 0 = … : …
replaceWithS (x:xs) i = … : replaceWithS … …

Here x is thus the head of the string (its first character), and xs is a list with the remaining characters. You here still need to fill in the parts.

Upvotes: 1

Related Questions