Haskell替换字符串中的字符

MrD*_*MrD 11 haskell

假设我有一个字符串"HELLO WORLD"有一种方法我可以调用一个函数来替换字符串中的字符"O"和字符"X",以便新字符串看起来像"HELLX WXRLD"?

Ing*_*ngo 33

怎么样:

let 
    repl 'o' = 'x'
    repl  c   = c
in  map repl "Hello World"
Run Code Online (Sandbox Code Playgroud)

如果以后需要替换其他字符,只需在repl函数中添加子句即可.

  • 模式匹配是王道. (3认同)

Arn*_*non 10

很抱歉拿起这个旧线程,但为什么不使用lambda表达式?

?> let replaceO = map (\c -> if c=='O' then 'X'; else c)
?> replaceO "HELLO WORLD"
"HELLX WXRLD"`
Run Code Online (Sandbox Code Playgroud)


Lei*_*ork 8

备选方案1 - 使用MissingH

第一:

import Data.List.Utils (replace)
Run Code Online (Sandbox Code Playgroud)

然后使用:

replace "O" "X" "HELLO WORLD"
Run Code Online (Sandbox Code Playgroud)

备选方案2 - 使用Control.Monad

一个有趣的混蛋:

import Control.Monad (mfilter)

replace a b = map $ maybe b id . mfilter (/= a) . Just
Run Code Online (Sandbox Code Playgroud)

例:

?> replace 'O' 'X' "HELLO WORLD"
"HELLX WXRLD"
Run Code Online (Sandbox Code Playgroud)

备选方案3 - 使用if

阿蒙的建议可能是我认为最好的!没有进口,易于阅读和理解!

但要挑剔 - 不需要分号:

replace :: Eq a => a -> a -> [a] -> [a]
replace a b = map $ \c -> if c == a then b else c
Run Code Online (Sandbox Code Playgroud)