假设已定义pos_of_xy(x,y)n以返回int,则一旦if语句之一返回false,此代码段将退出,就好像它们是嵌套的一样.无论先前的if语句如何,我都需要它们全部运行.我不确定我忘记了什么.
let final = ref [] in begin
if x < (size-1) then let pos = pos_of_xy (x+1, y) size in final := pos::!final;
if y < (size-1) then let pos = pos_of_xy (x, y+1) size in final := pos::!final;
if y > 0 then let pos = pos_of_xy (x, y-1) size in final := pos::!final;
if x > 0 then let pos = pos_of_xy (x-1, y) size in final := pos::!final;
end;
Run Code Online (Sandbox Code Playgroud)
描述问题的一种方法let是强于if.A之后let接受一系列语句in,后续的ifs被视为该序列的一部分.如果你用括号括起来,事情应该有效let:
if x < size - 1 then
(let pos = pos_of_xy (x + 1, y) size in final := pos :: !final);
Run Code Online (Sandbox Code Playgroud)
或者你可以没有let:
if x < size -1 then final := pos_of_xy (x + 1, y) size :: !final;
Run Code Online (Sandbox Code Playgroud)
作为一个侧面评论,如果您使用更具功能性的样式(没有可变值),则代码可能看起来更好于FP编程器.
更新
这是一个计算列表的更实用方法的快速草图:
let good (x, y) = x >= 0 && x < size && y >= 0 && y < size in
let topos (x, y) = pos_of_xy (x, y) size in
let goodxy =
List.filter good [(x + 1, y); (x, y + 1); (x - 1, y); (x, y - 1)] in
List.map topos goodxy
Run Code Online (Sandbox Code Playgroud)