In my best Homer Simposon voice - "unfoldr - is there anything it can't do?"

I have strange unfoldr love right now. I'm probably too impressed by
this function, but it takes a string and splits it into a list of
words, while keeping "quoted" phrases together:

    import Data.List

    phrasesAndWords :: String -> [String]
    phrasesAndWords =
      let startsWith w c = [c] `isPrefixOf` w
          endsWith w c = [c] `isSuffixOf` w
          buildPhrases [] = Nothing
          buildPhrases (w:ws)
            | w `startsWith` '"' = -- A word starts with a '"', now
look for ending '"'
                let (p, rest) = break (`endsWith` '"') (w:ws)
                in
                  case () of
                    () | null p -> Just ((init . tail) w, ws) --
single word in quotes
                       | null rest -> Just ((tail . unwords) p, rest)
-- No ending quote
                       -- Some amount of words in the phrase and some not
                       | otherwise -> Just ((init . tail) (unwords (p
++ [head rest])), tail rest)
            | otherwise = Just (w, ws)
      in
        -- Use of words makes sure any valid quotes appear at beginning or
        -- end of a word.
        unfoldr buildPhrases . words

Of course it's not a full parser (no nested quotes or escaping) but
who would think unfoldr could do that?

Justin

p.s. Style comments, improvements welcome.
_______________________________________________
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe

Reply via email to