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>import Data.Maybe (isNothing, fromJust)
<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
(tokens, parts, offset) =
(ts, ps, o) =
foldl
foldl
(\(tokens, parts, offset) (c, i) ->
(\(tokens, parts, offset) (c, i) ->
let inDelim = offset > i
let inDelim = offset > i
mb =
in case (if inDelim
if inDelim
then Nothing
then Nothing
else find (`isPrefixOf` drop i s) ds) of
else find (`isPrefixOf` drop i s) ds
Just x -> ([], mappend parts [(tokens, x, i)], i + length x)
in if isNothing mb
Nothing ->
then ( mappend
( mappend
tokens
tokens
(if inDelim
(if inDelim
then []
then []
else [c])
else [c])
, parts
, parts
, offset)
, offset))
else ( []
, mappend parts [(tokens, fromJust mb, i)]
, i + length (fromJust mb)))
([], [], 0)
([], [], 0)
(zip s [0 .. lng])
(zip s [0 .. lng])
in mappend parts [(tokens, [], lng)]
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>