Suppose I have a list like this one:
list= [["a","123","b"],["h","435","t"],["w","234","j"]]
What I need is to convert each second member of that list of lists into an Integer
because it will serve as a size indicator after that so I can sort my list by size.
I've came up with a function for conversion:
charToInt c = ord (chr c)
but I dont know how to convert each second member of the list.
To expand on what Paul Johnson said, you need to define a datatype for the data you're trying to hold.
data MusicFile = MusicFile {music :: String,
size :: Integer,
artist :: String}
deriving Show
musicFileFromStrings :: [String] -> MusicFile
musicFileFromStrings [sMusic, sSize, sArtist]
= MusicFile sMusic (read sSize) sArtist
Then if you have
list = [["a","123","b"],["h","435","t"],["w","234","j"]]
you can say
anotherList = map musicFileFromStrings list
and then
map music anotherList -- ["a", "h", "w"]
map artist anotherList -- ["b", "t", "j"]
(EDIT)
If you want to sort the list by a particular field you can use "sortBy" and " comparing ".
import Data.List
import Data.Ord
sizeOrderList = sortBy (comparing size) anotherList
The "comparing" function turns a function on a value (in this case "size") into a comparison function between two values. The only requirement is that the output of "size" (in this case) be a type that is an instance of "Ord".
If you want descending order than use
sizeOrderList = sortBy (comparing (flip size)) anotherList
You cannot convert the second element of the inner lists to an Integer
without changing the type from a list to something like a tuple. The reason is that lists are homogeneous in Haskell, so you need a tuple to represent mixed types.
Converting a String
into an Integer
is done like this:
read "123" :: Integer
You need to add the type directly since the type of read
is Read a => String -> a
, meaning that it'll return something of a type that can be "read". Luckily, Integer
is a member of that type class, so we can convert String
into Integer
.
Now it's just a simple matter of converting the second element of each inner list:
convert :: [[String]] -> [(String, Integer, String)]
convert lists = map (\[a, b, c] -> (a, read b, c)) lists
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.