1

如果给出不合适的参数,我想尽早退出函数Javascript中的命令式解决方案很优雅:

arg=>{
	if(arg>limit) return 42;
	//perform complex operations
	return x+y
}

ReasonML 作为一种函数式语言没有return,因此我将所有内容都填充到单个表达式中:

arg=>{
    let helper=()=>{
        //complex operations here
        ; x+y
    }
    (arg>limit) ? 42 : helper()
}

现在,这行得通,但不是只返回 42 我想填充Js.Log("!CORNER CASE!"). 我怎样才能做到这一点?在 C 中,我可以编写(arg>limit) ? (Js_Log("..."),42) : helper(),但在 ReasonML 中,这变成了一个元组并且无法编译。

OCaml 可以begin printf "msg" ; 42 end,但分号在原因中对我不起作用:(Js.log("TEST");42)- 无法编译!

或者,我需要 ReasonML 中的 K-combinator。

4

1 回答 1

2

我看不出只是使用有什么问题

if (arg > limit) {
  Js_Log("...");
  42
} else {
  //complex operations here
  x + y
}

但是如果你绝对必须挤进三元条件,你也可以使用花括号在那里形成一个代码块,通常在任何你可以放置表达式的地方:

arg > limit ? {Js.log("..."); 42} : helper()

我通常会认为这是一种代码异味,但为了快速调试,它可能很方便。

于 2020-04-05T18:05:28.483 回答