[Haskell-beginners] beginner question

Daniel Fischer daniel.is.fischer at web.de
Fri Oct 30 10:46:33 EDT 2009


Am Freitag 30 Oktober 2009 14:40:13 schrieb Luca Ciciriello:
> Hi all.
>
> Just a very basic question.
>
>
>
> I need to write a function str2lsts :: String -> [[String]] in order to
> transorm a string like:
>
>
>
> "\"1\",\"cat\",\"dog\"§\"2\",\"duck\",\"goose\""
>
>
>
> in the list of lists:
>
>
>
> [["1","cat","dog"],["2","duck","goose"]]
>
>
>
> I've tried to mix recursion, pattern matching and list comprehension, but
> the obtained result was embarrassing complex (> 20 lines of awful code). I
> think that a more simple solution certainly exists.
>

splitOnToken :: Eq a => a -> [a] -> [[a]]
splitOnToken t xs
    = case break (== t) xs of
        (hd,tl) -> hd:case tl of
                    (_:r@(_:_)) -> splitOnToken t r
                    _ -> []

str2lsts = map (map read . splitOnToken ',') . splitOnToken '§'

if things weren't enclosed in quotation marks inside the string, it would be the nicer

map (splitOnToken ',') . splitOnToken '§'

, provided of course, neither ',' nor '§' are valid characters for the target strings.

import Text.ParserCombinators.Parsec

simple = between (char '"') (char '"') (many (staisfy (/= '"')))
-- alternative: simple = char '"' >> manyTill anyChar (char '"')

multiple = sepBy simple (char ',')

total = sepBy multiple (char '§')

str2lsts str
    = case parse total "" str of
        Left err -> error (show err)
        Right lsts -> lsts

>
>
>
> Thanks in advance for any idea.
>
>
>
> Luca




More information about the Beginners mailing list