Jump to content

Multisplit: Difference between revisions

→‎{{header|Haskell}}: Additional example (multisplit by fold)
No edit summary
(→‎{{header|Haskell}}: Additional example (multisplit by fold))
Line 673:
with [(string, delimiter, offset)]:
[("a","!=",1),("","==",3),("b","=",6),("","!=",7),("c","",10)]</pre>
 
Or as a fold:
 
<lang haskell>module Multisplit where
 
import Data.Maybe (isNothing, fromJust)
import Data.List (find, isPrefixOf)
 
multiSplit :: [String] -> String -> [(String, String, Int)]
multiSplit ds s =
let lng = length s
(tokens, parts, offset) =
foldl
(\(tokens, parts, offset) (c, i) ->
let inDelim = offset > i
mb =
if inDelim
then Nothing
else find (`isPrefixOf` drop i s) ds
in if isNothing mb
then ( mappend
tokens
(if inDelim
then []
else [c])
, parts
, offset)
else ( []
, mappend parts [(tokens, fromJust mb, i)]
, i + length (fromJust mb)))
([], [], 0)
(zip s [0 .. lng])
in mappend parts [(tokens, [], lng)]
 
main :: IO ()
main = print $ multiSplit ["==", "!=", "="] "a!===b=!=c"
</lang>
{{Out}}
<pre>[("a","!=",1),("","==",3),("b","=",6),("","!=",7),("c","",10)]</pre>
 
=={{header|Icon}} and {{header|Unicon}}==
9,659

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.