[topic] すべて置換

文字列中のマッチする部分をすべて置換する方法について。

Posted feedbacks - Haskell

なんかもっとシンプルに書けそうな気もするのですが。。。
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
--
--  文字列の置き換え
--
  
module Main where
  
import Data.List
  
replace :: String -> String -> String -> String
replace _ _ "" = ""
replace "" _ all = all
replace inp out all@(s:ss)
    | isPrefixOf inp all    = out ++ replace inp out (drop (length inp) all)
    | otherwise             = s : replace inp out ss
  
main = do
    putStrLn $ show $ replace "abc" "ABC" "abcdefgabcdefg"

Index

Feed

Other

Link

Pathtraq

loading...