[英]Haskell: Convert String to [(String,Double)]
I parse an XML and get an String like this:我解析一个 XML 并得到一个这样的字符串:
"resourceA,3-resourceB,1-,...,resourceN,x"
"resourceA,3-resourceB,1-,...,resourceN,x"
I want to map that String into a list of tuples (String,Double), like this:我想将该字符串映射到元组列表 (String,Double) 中,如下所示:
[(resourceA,3),(resourceB,1),...,(resourceN,x)]
[(resourceA,3),(resourceB,1),...,(resourceN,x)]
How is it possible to do this?怎么可能做到这一点? I ve looked into the map function and also the split one.
我已经研究了 map 函数和 split 函数。 I am able to split the string by "-" but anything else...
我可以用“-”分割字符串,但其他任何东西......
This is the code i have so far:这是我到目前为止的代码:
split :: Eq a => a -> [a] -> [[a]]
split d [] = []
split d s = x : split d (drop 1 y) where (x,y) = span (/= d) s
it is just a function to split my string into a list of Stirng, but then i dont know how to continue.它只是将我的字符串拆分为 Stirng 列表的函数,但是我不知道如何继续。 What I want to do know is to loop over that new list that i have created with the split method and for each element create a tuple.
我想知道的是循环遍历我用 split 方法创建的新列表,并为每个元素创建一个元组。 I hace tried with the map function but i dont get it to compile even
我曾尝试使用 map 函数,但我什至无法编译它
So in Haskell you dont really mutate any value, instead you'll create a new list of pairs from the string you've described, so the solution would look something similar to the following:因此,在 Haskell 中,您不会真正改变任何值,而是根据您描述的字符串创建一个新的对列表,因此解决方案看起来类似于以下内容:
import Data.List.Split
xmlList = splitOn "-" "resourceA,3-resourceB,4-resourceC,6"
commaSplit :: String -> [String]
commaSplit = splitOn ","
xmlPair :: [String] -> [(String, Double)] -- might be more efficient to use Text instead of String
xmlPair [x] = [(\x' -> ((head x') :: String, (read (last x')) :: Double )) (commaSplit x)]
xmlPair (x:xs) = xmlPair [x] ++ xmlPair xs
main :: IO ()
main = mapM_ (\(a,b) -> putStrLn (show a++" = "++ show b)) (xmlPair $ xmlList)
This is my quick and dirty way of showing things but I'm sure someone can always add a more detailed answer.这是我展示事物的快速而肮脏的方式,但我相信总有人可以添加更详细的答案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.