问题
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.
For example
"1,2,-5,-23,15" -> [2,3,-4,-22,16]
Below is the resulting program
import Data.List
main :: IO ()
main = do
n <- return 1
putStrLn . show . map (+1) . map toInt . splitByDelimiter delimiter
$ getList n
getList :: Int -> String
getList n = foldr (++) [] . intersperse [delimiter] $ replicate n inputStr
delimiter = ','
inputStr = "1,2,-5,-23,15"
splitByDelimiter :: Char -> String -> [String]
splitByDelimiter _ "" = []
splitByDelimiter delimiter list =
map (takeWhile (/= delimiter) . tail)
(filter (isPrefixOf [delimiter])
(tails
(delimiter : list)))
toInt :: String -> Int
toInt = read
The most hard part for me was programming of function splitByDelimiter
that take a String and return list of Strings
"1,2,-5,-23,15" -> ["1","2","-5","-23","15"]
Thought it is working, I am not happy with the way it is written. There are a lot of parentheses, so it looks Lisp like. Also the algorithm is somewhat artificial:
Prepend delimiter to beginning of string
",1,2,-5,-23,15"
Generate list of all tails
[",1,2,-5,-23,15", "1,2,-5,-23,15", ",2,-5,-23,15", .... ]
Filter and left only strings that begins with delimiter
[",1,2,-5,-23,15", ",2,-5,-23,15", .... ]
Drop first delimiter and take symbols until next delimiter will be met
["1", "2", .... ]
So the questions are:
How I can improve function splitByDelimiter
?
Can I remove prepend and drop of delimiter and make direct split of string?
How I can rewrite the function so there will be less parentheses?
May be I miss something and there are already standard function with this functionality?
回答1:
Doesn't Data.List.Split.splitOn do this?
回答2:
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"]
回答3:
This is a bit of a hack, but heck, it works.
yourFunc str = map (+1) $ read ("[" ++ str ++ "]")
Here is a non-hack version using unfoldr
:
import Data.List
import Control.Arrow(second)
-- break' is like break but removes the
-- delimiter from the rest string
break' d = second (drop 1) . break d
split :: String -> Maybe (String,String)
split [] = Nothing
split xs = Just . break' (==',') $ xs
yourFunc :: String -> [Int]
yourFunc = map ((+1) . read) . unfoldr split
回答4:
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>
回答5:
This is application of HaskellElephant's answer to original question with minor changes
splitByDelimiter :: Char -> String -> [String] splitByDelimiter = unfoldr . splitSingle splitSingle :: Char -> String -> Maybe (String,String) splitSingle _ [] = Nothing splitSingle delimiter xs = let (ys, zs) = break (== delimiter) xs in Just (ys, drop 1 zs)
Where the function splitSingle split the list in two substrings by first delimiter.
For example:
"1,2,-5,-23,15" -> Just ("1", "2,-5,-23,15")
回答6:
splitBy del str = helper del str []
where
helper _ [] acc = let acc0 = reverse acc in [acc0]
helper del (x:xs) acc
| x==del = let acc0 = reverse acc in acc0 : helper del xs []
| otherwise = let acc0 = x : acc in helper del xs acc0
回答7:
This code works fine use:- split "Your string" [] and replace ',' with any delimiter
split [] t = [t]
split (a:l) t = if a==',' then (t:split l []) else split l (t++[a])
回答8:
import qualified Text.Regex as RegExp
myRegexSplit :: String -> String -> [String]
myRegexSplit regExp theString =
let result = RegExp.splitRegex (RegExp.mkRegex regExp) theString
in filter (not . null) result
-- using regex has the advantage of making it easy to use a regular
-- expression instead of only normal strings as delimiters.
-- the splitRegex function tends to return an array with an empty string
-- as the last element. So the filter takes it out
-- how to use in ghci to split a sentence
let timeParts = myRegexSplit " " "I love ponies a lot"
回答9:
Another without imports:
splitBy :: Char -> String -> [String]
splitBy _ [] = []
splitBy c s =
let
i = (length . takeWhile (/= c)) s
(as, bs) = splitAt i s
in as : splitBy c (if bs == [] then [] else tail bs)
来源:https://stackoverflow.com/questions/4503958/what-is-the-best-way-to-split-a-string-by-a-delimiter-functionally