返回矩形范围内的单元列表

问题描述 投票:0回答:3

作为OCAML的初学者,我正在尝试编写一个函数,该函数需要两个INT参数(A和B),并且应返回一个包含所有元组(i,j)的列表,其中我在0和A之间,而J在0和B之间,顺序无关紧要。 该功能应该是这样的:myFunc:int-> int->(int*int)列表 结果必须是[(0,1);(0,2)] ...

我已经写了一个函数,该函数接受了两个INT参数,并在这两个函数之间返回列表。例如,1和5给我这个列表:[1; 2; 3; 4; 5]。 这就是我所做的:

let rec btwn = fun a b -> if a>b then []
                       else if a = b then [a]
                       else a :: btwn (a+1) b ;;
我的想法是重复使用此功能,并创建两个列表:一个带有范围0的列表; A和彼此的范围为0; b,然后用这两个列表制作所有元组。 我听说过list.fold_left/正确,list.map,但我无法正常工作... 你有什么想法吗?谢谢!

ocaml fold
3个回答
0
投票
如果您想重复使用

btwn

,您基本上想实现此::

fun a b -> let la = btwn 0 a and lb = btwn 0 b in cartesian_product la lb;;
现在,您只需要实现

cartesian_product

,这基本上是两个嵌套循环:元素的外回路迭代
a
la
中,对于每个e,您都可以在所有元素上迭代所有元素。 a
构建列表
b
,...,
lb
。然后,您必须加入所有列表(
[(ai,b0)
,然后是
(ai,bj)]
等)。 pseudo代码,那将是:
a0
但是,您可以在参数和中间返回值中将结果列表进行线程线索,以确保您始终仅在前面添加元素,这需要持续的时间:
a1

如果您不介意拥有局部可变状态,那么一种更简单的方法就是:

R = []
loop for a in la:
  R := append(R, [(a,b) for b in lb])

以下代码有效:

let cross_product la lb = let rec outer sofar la = match la with | [] -> sofar | a::la -> let rec inner sofar lb = match lb with | [] -> sofar | b::lb -> (inner ((a,b)::sofar) lb) in outer (inner sofar lb) la in outer [] la;;

代码通过迭代两个给定索引0
来起作用

0
投票

对于

open List;;
let cross_product la lb =
  let stack = ref []
  in iter (fun a -> iter (fun b -> stack := (a,b)::!stack) lb) la;
     !stack;;

和< i < n and 0 < j < m ; The first helper function creates tuples of the form (0,j), (1,j)...,(n,j).Basically iterating through I given a fixed j. And the second iterate through values of j.


0
投票

(创建一个“平面”列表)。 List.map

    
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.