What is the best way to split a string by a delimiter functionally?

后端 未结 9 1781
死守一世寂寞
死守一世寂寞 2020-12-29 22:11

I tried to write the program in Haskell that will take a string of integer numbers delimitated by comma, convert it to list of integer numbers and increment each number by 1

9条回答
  •  一整个雨季
    2020-12-29 22:36

    Just for fun, here is how you could create a simple parser with Parsec:

    module Main where
    
    import Control.Applicative hiding (many)
    import Text.Parsec
    import Text.Parsec.String
    
    line :: Parser [Int]
    line = number `sepBy` (char ',' *> spaces)
    
    number = read <$> many digit
    

    One advantage is that it's easily create a parser which is flexible in what it will accept:

    *Main Text.Parsec Text.Parsec.Token> :load "/home/mikste/programming/Temp.hs"
    [1 of 1] Compiling Main             ( /home/mikste/programming/Temp.hs, interpreted )
    Ok, modules loaded: Main.
    *Main Text.Parsec Text.Parsec.Token> parse line "" "1, 2, 3"
    Right [1,2,3]
    *Main Text.Parsec Text.Parsec.Token> parse line "" "10,2703,   5, 3"
    Right [10,2703,5,3]
    *Main Text.Parsec Text.Parsec.Token> 
    

提交回复
热议问题