I came up with this function rangedReplace
as an exercice to use recursion and try different ways to make it work (I made at least 3 completely different versions). I think this version is the best but I have a feeling I can improve the way the functions/arguments are handled especially in the censor
and in the main
functions. How can I get these functions to be more idiomatic Haskell-way of doing, ?
-- Replace the letters in the range [from:to[ ("to" not included) with chr
rangedReplace :: Int -> Int -> Char -> String -> String
rangedReplace from to chr str
| from == to = str
| otherwise = (take from' str) ++ rangedReplace' chr n (drop from' str)
where from' = min from to
to' = max from to
n = to' - from'
-- Helper function
rangedReplace' :: Char -> Int -> String -> String
rangedReplace' chr n str
| n == 0 = str
| str == "" = ""
| otherwise = chr : (rangedReplace' chr (n-1) (tail str))
Usage example:
censor (from,to) = rangedReplace from to '*'
main = do
putStrLn $ foldr id "Fork bombs" (map censor [(1,3),(6,8)])