Permutations of two lists

断了今生、忘了曾经 提交于 2020-01-24 22:01:13

问题


I have a char list in OCAML. I would like to create a ( (char * bool) list) list of every combination of the chars with true and false.

What I have guess I have to do is something like a List.fold_left, but I am not quite sure how to pull it off.

This is the outline that I tried (OCAML syntax, but not run-able):

let rec var_perm var_list options = 
    match var_list with
        | [] -> options
        | x :: v' ->
            ((x, true) :: (var_perm_intern v')) :: ((x, false) :: (var_perm_intern v'))
;;

let all_options = var_perm ['a';'b'] [];;

should return

[
    [('a',true);('b',true)];
    [('a',true);('b',false)];
    [('a',false);('b',true)];
    [('a',false);('b'false)];
]

Edit: Another example:

let all_options = var_perm ['u';'w';'y'] [];;

should return (order is not important)

[
    [('u',false);('w',false);('y',false)];
    [('u',false);('w',false);('y',true )];
    [('u',false);('w',true );('y',false)];
    [('u',false);('w',true );('y',true )];
    [('u',true );('w',false);('y',false)];
    [('u',true );('w',false);('y',true )];
    [('u',true );('w',true );('y',false)];
    [('u',true );('w',true );('y',true )];
]

回答1:


You're close to a correct solution. Specifically:

  • you must remove the _intern suffix in your recursive call
  • the "options" parameter is useless (look at how you do your recursive call, passing only one parameter v'), so you must find out what to return in the [] case
  • the concatenation of "the results of v', plus true for the head var" and " the results of v', plus false for the head var" should be written foo @ bar rather than foo :: bar, because those are two lists you're concatenating, not one element added to a list.


来源:https://stackoverflow.com/questions/14740866/permutations-of-two-lists

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!