Reputation: 81
I want to generate all possible combinations between two lists. For example, if I had list1: [1,2] and list2: [a,b]. It would produce a list that contains [(1,a),(1,b),(2,a),(2,b)]. I am trying to figure out how to do this with recursion and match expressions. I am currently stuck with this:
let rec combo (a1: 'a list) (a2: 'b list) =
match a1,a2 with
| [],[] -> []
Upvotes: 0
Views: 373
Reputation: 1031
Divide your task. First, write a function that returns a list of pairs formed from a single value and the items in a list (it'll be your second list).
let rec makePairs x lst acc =
match lst with
| [] -> acc
| _ -> makePairs x (List.tail lst) (acc @ [(x, List.head lst)])
// makePairs 'a' [5;7] [] yields [('a',5), ('a',7)]
Then, by the same pattern as in makePairs
, write a function makeAllPairs lst1 lst2 acc
that enumerates the items of the first list and collects the pairs for the item returned from makePairs
.
A simpler version of makePairs:
let makePairs2 x lst = List.map (fun b -> (x, b)) lst
Upvotes: 0