Rado
Rado

Reputation: 9

how to find a certain char in string and replacing it with the spaces, left in that string with anonymous function in haskell

I need to write a function ,with the use of foldl, which recieves a string "str" and returns an anonymous function. The anonymous functions receives a char 'c' and exchanges every instance of 'c' in "str" with the remaining number of chars in the string "str"

                          speak :: String -> (Char -> String)

example:

"Hello" 'e' -> "H3llo"

"gate" 't' -> "ga1e"

I've tried this code, but cant get it to work properly:

speak :: String -> (Char ->String)
speak str = foldl (\x -> if x == str then x = show(length str) else str) str 

Upvotes: 1

Views: 175

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476709

You can not assign a value to x What you need to do is either return show (length xs) ++ xs in case the character x is the same as the one you are looking for, or x:xs (so a normal prepend of x to xs) in case it does not match. Your speak also has a Char as first parameter, and then converts a String to a String, so:

speak :: Char -> String -> String
speak c = foldr (\x xs -> if c == x then show (length xs) ++ xs else (x:xs))

or with swapped parameters:

speak :: String -> Char -> String
speak str c = foldr (\x xs -> if c == x then show (length xs) ++ xs else (x:xs)) str

Upvotes: 2

Related Questions