如何修复替换Haskell功能?

发布于 2025-02-11 02:08:20 字数 408 浏览 0 评论 0 原文

它可以工作时:替换:: eq a => a - > a - > [a] - > [a]会。如何将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"

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"

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

最笨的告白 2025-02-18 02:08:20

您正在使用错误的操作员作为第一个后卫( 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

相关 - haskell(:)和(++)差异

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文