Anil
Anil

Reputation: 175

Where is the mistake in this replacing function in Haskell?

I want to write a function which takes a string and replaces any number in the string with 7. For example "foo123" will be replaced to "foo777"

This is my function.

replace [] = []
replace (x:xs) =
    if x == ['0'..'9']
    then '7' : replace xs
    else x : replace xs

Upvotes: 0

Views: 157

Answers (2)

chepner
chepner

Reputation: 531948

== does not test if x is an element of the list; it checks if x is equal to the list. Use the elem function instead.

replace [] = []
replace (x:xs) =
    if x `elem` ['0'..'9']
    then '7' : replace xs
    else x : replace xs

if is a pure expression that can be used anywhere another expression can be used, so you don't need to repeat the recursive call to xs:

replace [] = []
replace (x:xs) = (if x `elem` ['0'..'9'] then '7' else x) : replace xs

Finally, you can just use map instead of using explicit recursion.

replace xs = map (\x -> if x `elem` ['0'..'9'] then '7' else x) xs

or just

replace = map (\x -> if x `elem` ['0'..'9'] then '7' else x)

You may want to use Data.Char.isDigit instead:

import Data.Char
replace = map (\x -> if isDigit x then '7' else x)

Upvotes: 6

Sylvain Attoumani
Sylvain Attoumani

Reputation: 1194

== only tests if x is equal to the list, which it is not. You have to use the function elem which takes as its parameter one element and a list of element, and returns true if the element is in the list. So your code will be:

replace [] = []
replace (x:xs) =
    if elem x ['0'..'9']
    then '7' : replace xs
    else x : replace xs

Upvotes: 2

Related Questions