Cutting a string to a list in Haskell?

Is it possible to cut a string, for example

"one , Two"

to the list

["one", "two"]

or simply

"one", "two"

thank

+3
source share
4 answers

There is a whole module of functions for different strategies for splitting a list (for example, a string that is just a list of characters): Data.List. Split

Using this, you can do

import Data.List.Split

> splitOn " , " "one , Two"
["one","Two"]
+7
source

There are enough regular operations with the old list,

import Data.Char

> [ w | w <- words "one , Two", all isAlpha w ]
["one","Two"]

aka

> filter (all isAlpha) . words $ "one , Two"
["one","Two"]

Hacking, parsing and design list

In word processing, there is a scale of power and weight. The simplest list-based solutions, such as the ones above, offer very little syntax noise for quick results (in the same spirit as quick'n'dirty text processing in shell scripts).

, , . split,

> splitOn " , " "one , Two"
["one","Two"]

, , . , , , parsec uu-parsinglib. , , , , , , .

: () , " " " ". , .

+2

split package (. ), splitOn, :

import Data.List

splitOn :: Eq a => [a] -> [a] -> [[a]]
splitOn []    _  = error "splitOn: empty delimiter"
splitOn delim xs = loop xs
    where loop [] = [[]]
          loop xs | delim `isPrefixOf` xs = [] : splitOn delim (drop len xs)
          loop (x:xs) = let (y:ys) = splitOn delim xs
                         in (x:y) : ys
          len = length delim
+2

, Parsec. , .

firstElement :: Parser String
firstElement = many $ noneOf ' '

otherElement :: Parser String
otherElement = do many $ char ' '
                  char ','
                  many $ char ' '
                  firstElement

elements :: Parser [String]
elements = liftM2 (:) firstElement (many otherElement)

parseElements :: String -> [String]
parseElements = parse elements "(unknown)"

otherElement - , , elements liftM2.

0

All Articles