如果在OCaml中为false,则If语句会提前结束函数

如果在OCaml中为false,则If语句会提前结束函数,ocaml,Ocaml,假设已经定义了_xy(x,y)n的pos_来返回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 = p

假设已经定义了_xy(x,y)n的pos_来返回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;
begin中的final=ref[]
如果x<(尺寸-1),则让pos=pos\u of_xy(x+1,y)的最终尺寸:=pos:!最终的
如果y<(大小-1),则让pos=pos\u of_xy(x,y+1)大小在final:=pos:!最终的
如果y>0,则让pos=pos\u的大小为xy(x,y-1)的final:=pos:!最终的
如果x>0,则让pos=pos\u在final:=pos:!最终的
结束;

描述问题的一种方式是
let
if
更强。
let
在中的
之后获取一系列语句,如果
被视为该序列的一部分,则后续的
。如果您将每个
插入括号,事情应该会顺利进行

if x < size - 1 then
    (let pos = pos_of_xy (x + 1, y) size in final := pos :: !final);
if x < size -1 then final := pos_of_xy (x + 1, y) size :: !final;
作为旁注,如果您使用更具功能性的风格(没有可变值)编写代码,那么对于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
让good(x,y)=x>=0&&x=0&&y
正如杰弗里·斯科菲尔德(Jeffrey Scofield)所说,
let
的优先级低于
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;
begin中的final=ref[]
如果x<(尺寸-1),则(设pos=pos_,of_xy(x+1,y)尺寸为(final:=pos:!final;
(如果y<(尺寸-1),则(设pos=pos_,of_xy(x,y+1))尺寸为(final:=pos:!final;
(如果y>0,那么(让pos=pos_为xy(x,y-1))的大小为(final:=pos:!final;
(如果x>0,则(让pos=pos_,大小为xy(x-1,y))的(final:=pos:!final;щщщщ))
结束;

您可以查看先例表(向上滚动一点)。如您所见,
if
的优先级高于
,它的优先级高于

谢谢!如何以更实用的方式实现这一点?我不需要确切的答案,但可能需要一个起点。更一般地说,除非
then
(或
else
)分支中的表达式非常琐碎,否则将其放在括号内(或
begin…end
)不会有什么坏处,这样你就不必问自己关于OCaml的先例的问题了。@AndrewM你可以这样做:
let l=[]in let l=if cond then x::l else l in let l=。。。在l
中(第一个和最后一个本地绑定是可选的,除非是为了模式的规则性)。或者,换句话说,
let
的优先级低于
if