Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell Convert List to List of Tuples

i have a list like this

["peter","1000","michell","2000","kelly","3000"]

and i would like to convert to

[("peter",1000),("michell", 2000),("kelly",3000)]

Please help. Thanks.

like image 869
nicholas Avatar asked Jun 18 '10 03:06

nicholas


2 Answers

cnv :: [String] -> [(String, Integer)]
cnv [] = []
cnv (k:v:t) = (k, read v) : cnv t

If you want to handle odd-length just add cnv [x] = variant before last one

like image 85
ony Avatar answered Oct 04 '22 02:10

ony


ony's solution is a bit shorter, but here's a non-recursive version using splitEvery from the very handy split library:

cnv = map (\[name, amount] -> (name, read amount :: Int)) . splitEvery 2

The steps here are somewhat clearer (for me, at least) than in the recursive version.

like image 22
Travis Brown Avatar answered Oct 04 '22 03:10

Travis Brown