简体   繁体   English

如何修复我的替换 haskell 功能?

[英]How can I fix my replace haskell function?

It eill work when : replace :: Eq a => a -> a -> [a] -> [a] will be.它会在以下情况下工作:replace :: Eq a => a -> a -> [a] -> [a] 将是。 How can I convert az a to an [a] in my code ?如何在我的代码中将 az a 转换为 [a] ?

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):您为第一个守卫( a == y )使用了错误的运算符 - :用于将头元素添加到列表中,但x是列表而不是单个元素,因此您需要使用++连接两个列表( x一个由递归调用返回):

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相关 - Haskell (:) 和 (++) 差异

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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