问题
I have a list of strings as follows;
["75","95 64","17 47 82"]
How can I convert this to a list of Ints;
[75,95,64,17,47,82]
My instinct is to use map and an anonymous function?
回答1:
Haskell has a few useful functions
read :: String -> Int -- Restricted for clarity
map :: (a -> b) -> [a] -> [b]
words :: String -> [String]
concatMap :: (a -> [b]) -> [a] -> [b]
So you give map
a function and a list and it will apply your function to each element of the list. Now knowing this, you should be able to solve it yourself.
As Gabriel pointed out you'll also need concatMap
and words
to make sure that your string only has 1 number in it. words
will split the string into a string of words and concatMap
will run it over each element and smash the result back together.
Do know that read will blow up in your face if you're not careful since if the string is malformed it will call error
which will terminate your program. If this is a concern, a similar process can be followed with
mapMaybe :: (a -> Maybe b) -> [a] -> [b]
readMaybe :: String -> Maybe Int -- Restricted for clarity
from Data.Maybe
and Text.Read
respectively.
回答2:
func theList = (map read . concat . map words) theList
you will need to specify the type when you use this unless it can be inferred
(func ["75","95 64","17 47 82"])::[Int]
来源:https://stackoverflow.com/questions/20384384/given-a-string-containing-numbers-what-is-the-best-way-to-extract-these