如何在字符串中找到某个字符并用空格代替它,在该字符串中使用匿名函数在Haskell中留下

发布于 2025-02-12 19:32:52 字数 458 浏览 0 评论 0原文

我需要使用 foldl 来编写一个函数 并返回一个匿名功能。匿名函数会接收一个字符“ C”,并与“ str”中的“ c”的每个实例与字符串“ str”示例中的剩余数量的字符

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

示例:

“ hello”''e' - > “ h3llo”

“ gate”'t' - > “ GA1E”

我尝试了此代码,但无法使其正常工作:

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

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 

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

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

发布评论

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

评论(1

爱*していゐ 2025-02-19 19:32:52

您无法将值分配给x您需要做的是返回show(长度xs)++ xs如果字符x与您要查找的一个或x:xs(因此,如果它确实确实如此不匹配。您的speak还将char作为第一个参数,然后将字符串转换为string,所以:

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

或交换参数:

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

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