Madalina
Madalina

Reputation: 85

Haskell replace specific characthers of a string

I've just started to learn haskell so this might be a really simple question..but here it is: I have a string, a charachter C and a number N. I need to write a function that replaces all the characthers from the position of the string that are divided by N with characther C. I must use list comprehension and only Base Function or Library function.

 replace::Char->Int->String->String 

Can someone please help me?

replace :: Int -> [Int] -> [Int]
replace y xs = [ if isDivided i then y else x | (i,x) <- zip [0..] xs ]

Upvotes: 0

Views: 157

Answers (1)

melpomene
melpomene

Reputation: 85767

Your approach is basically correct. If you change the type signature:

replace :: Char -> Int -> String -> String

and add another argument:

replace y d xs = [ if isDivisible i d then y else x | (i,x) <- zip [0..] xs ]

then you're almost done. You just have to write isDivisible.

Upvotes: 1

Related Questions