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

后端 未结 9 1829
死守一世寂寞
死守一世寂寞 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:54

    splitBy delimiter = foldr f [[]] 
                where f c l@(x:xs) | c == delimiter = []:l
                                 | otherwise = (c:x):xs
    

    Edit: not by the original author, but below is a more (overly?) verbose, and less flexible version (specific to Char/String) to help clarify how this works. Use the above version because it works on any list of a type with an Eq instance.

    splitBy :: Char -> String -> [String]
    splitBy _ "" = [];
    splitBy delimiterChar inputString = foldr f [""] inputString
      where f :: Char -> [String] -> [String]
            f currentChar allStrings@(partialString:handledStrings)
              | currentChar == delimiterChar = "":allStrings -- start a new partial string at the head of the list of all strings
              | otherwise = (currentChar:partialString):handledStrings -- add the current char to the partial string
    
    -- input:       "a,b,c"
    -- fold steps:
    -- first step:  'c' -> [""] -> ["c"]
    -- second step: ',' -> ["c"] -> ["","c"]
    -- third step:  'b' -> ["","c"] -> ["b","c"]
    -- fourth step: ',' -> ["b","c"] -> ["","b","c"]
    -- fifth step:  'a' -> ["","b","c"] -> ["a","b","c"]
    

提交回复
热议问题