两个列表的排列 [英] Permutations of two lists
本文介绍了两个列表的排列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在OCAML中有一个char list
.我想为char
与true
和false
的每种组合创建一个( (char * bool) list) list
.
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
.
我猜想我必须做的是List.fold_left
之类的东西,但是我不确定如何实现它.
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.
这是我尝试过的大纲(OCAML语法,但不可运行):
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'] [];;
应该返回
[
[('a',true);('b',true)];
[('a',true);('b',false)];
[('a',false);('b',true)];
[('a',false);('b'false)];
]
另一个示例:
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 )];
]
推荐答案
您已接近正确的解决方案.具体来说:
You're close to a correct solution. Specifically:
- 您必须在递归调用中删除
_intern
后缀 - "options"参数没有用(看看您如何递归调用,仅传递一个参数
v'
),因此您必须找出在[]
情况下返回的内容 - "
v'
的结果,加上true
代表头部var"和"v'
的结果,加上false
代表头部var"的串联应写为foo @ bar
而不是foo :: bar
,因为这是您要串联的两个列表,而不是一个元素添加到列表中.
- 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.
这篇关于两个列表的排列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文