[Haskell-cafe] How to split this string.

Christian Maeder Christian.Maeder at dfki.de
Mon Jan 2 11:29:58 CET 2012


Am 02.01.2012 10:44, schrieb max:
> I want to write a function whose behavior is as follows:
>
> foo "string1\nstring2\r\nstring3\nstring4" = ["string1",
> "string2\r\nstring3", "string4"]
>
> Note the sequence "\r\n", which is ignored. How can I do this?

replace the sequence by something unique first, i.e. a single "\r" (and 
revert this change later).

(Replacing a single character is easier using concatMap).

HTH Christian

-- | replace first (non-empty) sublist with second one in third
-- argument list
replace :: Eq a => [a] -> [a] -> [a] -> [a]
replace sl r = case sl of
   [] -> error "replace: empty list"
   _ -> concat . unfoldr (\ l -> case l of
     [] -> Nothing
     hd : tl -> Just $ case stripPrefix sl l of
       Nothing -> ([hd], tl)
       Just rt -> (r, rt))




More information about the Haskell-Cafe mailing list