问题
I have a char list
in OCAML. I would like to create a ( (char * bool) list) list
of every combination of the char
s 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'
, plustrue
for the head var" and " the results ofv'
, plusfalse
for the head var" should be writtenfoo @ bar
rather thanfoo :: 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