Reputation: 27
Given string lists [a, b, c] and [d, e] for example,
return the list [ad, bd, cd, ae, be, ce].
Please don't give me an answer, just a point the the right direction for a new learner.
Upvotes: -3
Views: 1064
Reputation: 41
After many years, just in case someone needs an answer, here is an elegant and efficient way to accomplish it:
let append_all xs ys =
let helper y =
List.map (fun x -> x^y) xs in
List.concat_map helper ys
Upvotes: 0
Reputation: 66823
This problem is tricky because you need to traverse two lists. If you write it as one function there are two recursions to keep track of.
One way to approach it is to start with a simpler problem. Say you have a list of strings l
and a string s
. Can you write a function that makes a new list with s
appended to each of the strings in l
?
There is a straightforward solution to this simpler problem using List.map
. Or you can write an explicitly recursive function.
After that you have only one remaining recursion to figure out, which may be easier.
Update
Now you have your function you can easily write a function that appends a string to all the elements of the first list of strings. The layout would look like this:
let cross_concat list1 list2 =
let concat_string_to_list1 s = concat_string_to_list list1 s in
...
With this definition, you can use List.map
again to get the final results (need to concatenate the resulting lists of strings into one list). Or you can use List.fold_right
to build up the result as you go. Or you can write your own recursive function.
If you haven't written too many recursive functions, this would be something to think through.
Upvotes: 2