简体   繁体   English

用 Haskell 替换字符串列表中的字符串

[英]Replace a string in list of strings with Haskell

i'am trying to create function that replace a given string in list of strings for exemple remplacer 'a' ["leaf","cacao"] gives a list ["le f","c co"]我正在尝试创建 function 来替换字符串列表中的给定字符串,例如remplacer 'a' ["leaf","cacao"]给出一个列表["le f","c co"]

with Haskell from this code:使用此代码中的 Haskell:

remplacer k = map(\c -> if c== k then ' '; else c)

once i do the call一旦我打电话

map remplacer "\r" ["abcd\r","alo\r"]

i got Couldn't match type 'char' with '[char]'我得到无法将类型“char”与“[char]”匹配

or result should be或者结果应该是

["abcd ","alo "]

Let's look at the types:让我们看一下类型:

map                :: (a -> b) -> [a] -> [b]
"\r"               :: [Char] -- Which is equivalent to String
["abcd\r","alo\r"] :: [[Char]] -- Same as [String]
remplacer          :: Char -> [Char] -> [Char]

Notice remplacer takes Char, not [Char].注意 remplacer 使用 Char,而不是 [Char]。 But replacing "\r" with '\r' alone won't work, because then we are making the first argument of map remplacer and the second '\r', in other words ((map remplacer) '\r') .但是单独用 '\r' 替换 "\r" 是行不通的,因为这样我们就制作了 map remplacer 的第一个参数和第二个 '\r',换句话说((map remplacer) '\r') This will not type check.这不会进行类型检查。 What we want is make ramplacer '\r' the first argument:我们想要的是让ramplacer '\r'成为第一个参数:

λ> map (remplacer '\r') ["abcd\r","alo\r"]
["abcd ","alo "]

Edit: I couldn't resist exploring your how map remplacer ".." would work.编辑:我忍不住探索你的map remplacer ".."是如何工作的。 For amusement, check how different of a function it is:为了娱乐,检查 function 有何不同:

λ> :t map remplacer "ab"
map remplacer "ab" :: [[Char] -> [Char]]
λ>  ($  "abc") <$> (map remplacer ['a', 'b'])
[" bc","a c"]

$ is simply \fa -> fa , regular function application. $只是\fa -> fa ,常规 function 应用程序。 The original question/answer uses map twice, this one uses map three times.原来的问答用了两次map,这个用了三次map。

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

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