ers,
I'm attempting to learn functional programming through ocaml and CYK tables, so no List.mem or any imperative functions for that matter. My objective is to form the product of 2 cells.
Here is what I currently have:
let stringlister = function(mystring, newlist) ->
List.append newlist mystring;;
let rec append_func = function([listleft;listright], anslist, i, j) ->
if (j == (List.length listright)) then anslist
else begin
append_func([listleft;listright], anslist, i, j + 1);
List.append(anslist (stringlister((List.nth listright j), (stringlister( (List.nth listleft i), [])))))
end;;
let rec prod_func = function([listleft;listright], anslist, i, j) ->
if (i == (List.length listleft)) then anslist
else begin
prod_func([listleft;listright], anslist, i + 1, j);
append_func([listleft;listright], anslist, i, j)
end;;
let product = function[listleft;listright] ->
if (listleft == [] || listright == []) then []
else prod_func([listleft;listright], [], 0, 0);;
The expected output should be something like this:
#product[["A";"B"];["D","E","F","G"]];;
-: string list = ["AD"; "AE"; "AF"; "AG"; "BD"; "BE"; "BF"; "BG"]
#product[["A","B"];[]];;
-: string list = []
My thought process was to make a series of recursive functions to basically loop through the lists to place each string with each string from another list.
I think my error is how I am appending, specifically in append_func. I think the better question to ask might be how to create a list of strings.
I'm new to Ocaml so maybe there's a different way
Of course it works for any amount of input lists
Maybe they read a little nicer using
function
We can approach the problem from another angle too. Notice the difference in the order of the output
Above
flat_map
calls the expensiveList.append
for each element in the list. A variation below collects the intermediate results and then builds the output with a single call toList.concat