简体   繁体   中英

How can I fix my replace haskell function?

It eill work when : replace :: Eq a => a -> a -> [a] -> [a] will be. How can I convert az a to an [a] in my code ?

replace :: Eq a => a -> [a] -> [a] -> [a]
replace _ _ [] = []
replace a x (y:ys)
 | a == y = x : replace a x ys
 | otherwise = y : replace a x ys

Example:

replace '?' "a" "" == ""
replace 'a' "e" "alma" == "elme"
replace 'a' "e" "nincsbenne" == "nincsbenne"

You are using wrong operator for the first guard ( a == y ) - : is used to prepend a head element to a list but x is a list not a single element, so you need to use ++ which concatenates two lists ( x and one returned by recursive call):

replace :: Eq a => a -> [a] -> [a] -> [a]
replace _ _ [] = []
replace a x (y:ys)
 | a == y = x ++ replace a x ys -- ++ instead of :
 | otherwise = y : replace a x ys

Related - Haskell (:) and (++) differences

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM