我需要在 OCaml 中测试一个 5 元素数组中的所有可能组合,如果任何组合满足条件,我必须停止 for 循环并返回该数组,但在 for 中返回一些东西并不容易...
我有这个代码:
let myfunction t =
let arraycolours = Array.make 5 W in
try
for i=0 to 3 do
Array.set arraycolours 0 (inttocolour i);
for j=0 to 3 do
Array.set arraycolours 1 (inttocolour j);
for k=0 to 3 do
Array.set arraycolours 2 (inttocolour k);
for l=0 to 3 do
Array.set arraycolours 3 (inttocolour l);
for m=0 to 3 do
Array.set arraycolours 4 (inttocolour m);
if test arraycolours = t then raise Exit
done
done
done
done
done
with Exit -> arraycolours;;
但是那里说: 错误:此表达式的类型为颜色数组 但是需要一个单位类型的表达式
如何返回满足条件的数组?
最佳答案
让我们用 <big-for-loop>
替换你的大 for 循环来折叠你的复杂函数定义。术语。
let myfunction t =
let arraycolours = Array.make 5 W in
try
<big-for-loop>
with Exit -> arraycolours
<big-for-loop>
实际上是一个表达式,其值为 ()
有类型单位。 try/with
表达式,语法如下:
try e1 with exn -> e2
两者e1
和 e2
必须返回相同类型的值。在你的情况下 <big-for-loop>
表达式返回 unit
类型的值和 with
下的表达式子句的类型为 colour array
.这基本上意味着,根据您是否能够找到组合,您的函数将具有不同的类型。但是 OCaml 中的类型不能依赖于运行时的值,所以我们有一个类型错误。
有不同的解决方案,具体取决于您尝试实现的内容,例如,您可以提出 Not_found
未找到组合时的异常,例如,
let myfunction t =
let arraycolours = Array.make 5 W in
try
<big-for-loop>;
raise Not_found
with Exit -> arraycolours
或者,您可以将结果包装成选项类型,并返回 Some array
如果找到该组合,则 None
否则:
let myfunction t =
let arraycolours = Array.make 5 W in
try
<big-for-loop>;
None
with Exit -> Some arraycolours
我个人更喜欢后一种解决方案。
关于arrays - OCaml 中的 "Break"for 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40949931/