Home > Enterprise >  Add Int to each String in list of lists of strings
Add Int to each String in list of lists of strings

Time:09-21

I need a function that takes a list of ints and a list of lists of strings, and adds the corresponding int to each string in the list like this:

addNumbers :: [Int] -> [[String]] -> [[(Int, String)]]

Example of how it should work:

addNumbers [1, 2] [["One", "Two"], ["Three", "Four"]]
-- output: 
[[(1, "One"), (2 "Two")], [(1, "Three"), (2, "Four")]]

I've come up with this using the zip function:

addNumbers :: [Int] -> [String] -> [(Int, String)]
addNumbers numbers strings = zip numbers strings

But this will obivously only work for a list of strings.

CodePudding user response:

You actually need a map too, to "get down a level" in lists.

addNumbers :: [Int] -> [[String]] -> [[(Int, String)]]
addNumbers numbers strings = map (zip numbers) strings

Then

λ addNumbers [1, 2] [["One", "Two"], ["Three", "Four"]]
[[(1, "One"), (2 "Two")], [(1, "Three"), (2, "Four")]]
λ
  • Related