【发布时间】:2021-08-02 22:52:23
【问题描述】:
练习是这样给出的:
- 创建函数翻转 val 翻转:bool 数组数组 -> int -> int -> bool 数组数组 = 给定一个布尔矩阵和两个整数 i, j。它否定了价值观 (真→假,假→真)在矩阵中的位置i,j,以及否定 (最多)4 个水平/垂直相邻元素的值。
这是我的功能:
let flip m a b=
for i=0 to ((Array.length m)-1) do
for j=0 to ((Array.length m.(1))-1) do
if i=a && j=b then
begin
m.(i).(j) <- not m.(i).(j);
try m.(i-1).(j) <- not m.(i-1).(j) with (Invalid_argument "index out of bounds") -> ();
try m.(i).(j-1) <- not m.(i).(j-1) with (Invalid_argument "index out of bounds") -> ();
try m.(i+1).(j) <- not m.(i+1).(j) with (Invalid_argument "index out of bounds") -> ();
try m.(i).(j+1) <- not m.(i).(j+1) with (Invalid_argument "index out of bounds") -> ();
end;
done;
done;
m;;
当我将此函数提供给任何类型的 2d bool 数组时,我会返回相同的数组,而不会对其进行任何更改。我做错了什么我没看到?
【问题讨论】:
-
您能否举例说明您为此函数提供的输入?
-
@ChrisDutton 是的,我声明了一个像这样的 3 x 4 矩阵:
let matrix =[|[|false; true; true; false|]; [|true; false; false; true|]; [|false; false; true; true|]|];;然后我通过像这样flip matrix 1 4;;的函数运行它,我得到相同的矩阵,没有对其进行任何更改.- : bool array array = [|[|false; true; true; false|]; [|true; false; false; true|]; [|false; false; true; true|]|] -
提示:如果你编辑你的问题,你可以更好地格式化这些东西。
-
您应该尝试通过尝试对
flip的其他输入来彻底测试您的代码。考虑寻找 1 和 4。OCaml 中的数组从 0 开始索引,因此 4 元素数组的上限永远不会大于 3,但您的条件最终会检查是否等于 4。您为什么要期待任何事情发生? -
@ChrisDutton 啊,是的,我明白了,谢谢!
标签: arrays function exception ocaml indexoutofboundsexception