Multisplit: Difference between revisions
Content added Content deleted
m (→{{header|Haskell}}: (Replaced one If with a `case ... of`)) |
|||
Line 676: | Line 676: | ||
Or as a fold: |
Or as a fold: |
||
<lang haskell> |
<lang haskell>multiSplit :: [String] -> String -> [(String, String, Int)] |
||
import Data.List (find, isPrefixOf) |
|||
multiSplit :: [String] -> String -> [(String, String, Int)] |
|||
multiSplit ds s = |
multiSplit ds s = |
||
let lng = length s |
let lng = length s |
||
( |
(ts, ps, o) = |
||
foldl |
foldl |
||
(\(tokens, parts, offset) (c, i) -> |
(\(tokens, parts, offset) (c, i) -> |
||
let inDelim = offset > i |
let inDelim = offset > i |
||
in case (if inDelim |
|||
then Nothing |
|||
else find (`isPrefixOf` drop i s) ds) of |
|||
Just x -> ([], mappend parts [(tokens, x, i)], i + length x) |
|||
Nothing -> |
|||
( mappend |
|||
tokens |
|||
(if inDelim |
|||
then [] |
|||
else [c]) |
|||
, parts |
|||
, offset)) |
|||
else ( [] |
|||
, mappend parts [(tokens, fromJust mb, i)] |
|||
, i + length (fromJust mb))) |
|||
([], [], 0) |
([], [], 0) |
||
(zip s [0 .. lng]) |
(zip s [0 .. lng]) |
||
in mappend |
in mappend ps [(ts, [], lng)] |
||
main :: IO () |
main :: IO () |
||
main = print $ multiSplit ["==", "!=", "="] "a!===b=!=c" |
main = print $ multiSplit ["==", "!=", "="] "a!===b=!=c"</lang> |
||
</lang> |
|||
{{Out}} |
{{Out}} |
||
<pre>[("a","!=",1),("","==",3),("b","=",6),("","!=",7),("c","",10)]</pre> |
<pre>[("a","!=",1),("","==",3),("b","=",6),("","!=",7),("c","",10)]</pre> |