从功能上说,用分隔符分割字符串的最佳方法是什么? [英] What is the best way to split a string by a delimiter functionally?
问题描述
我试图用Haskell编写程序,该程序将使用以逗号分隔的一串整数,将其转换为整数列表,并将每个数字加1.
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.
例如"1,2,-5,-23,15"->[2,3,-4,-22,16]
下面是生成的程序
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
对我来说,最难的部分是对函数 splitByDelimiter
进行编程,该函数需要一个字符串并返回字符串列表
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"]
考虑到它的工作原理,我对它的编写方式不满意.括号很多,所以看起来像Lisp.此外,该算法在某种程度上是人为的:
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:
-
将分隔符添加到字符串
,1,2,-5,-23,15"
生成所有尾巴的列表 [,1,2,-5,-23,15","1,2,-5,-23,15",,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", .... ]
删除第一个定界符并采用符号,直到满足下一个定界符为止. ["1","2",....]
Drop first delimiter and take symbols until next delimiter will be met ["1", "2", .... ]
所以问题是:
我如何改善功能 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?
推荐答案
不是 查看全文