How to create a sequence of actions mid-expression in ReasonML (and avoid creating a tuple)?

42 views Asked by At

I want to bail out of a function early, if given unsuitable arguments The imperative solution in Javascript is elegant:

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

ReasonML as a functional language has no return, thus I am stuffing everything into single expression:

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

Now, this works but instead of just returning 42 I want to stuff in Js.Log("!CORNER CASE!"). How can I do that? In C, I could write (arg>limit) ? (Js_Log("..."),42) : helper(), but in ReasonML this becomes a tuple and does not compile.

OCaml could do begin printf "msg" ; 42 end, but semicolon does not work for me in Reason: (Js.log("TEST");42) -- does not compile!

Alternatively, I need the K-combinator in ReasonML.

1

There are 1 answers

1
glennsl On BEST ANSWER

I don't see what's wrong with just using

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

but if you absolutely have to squeeze into a ternary conditional you can use curly braces to form a code block there too, and generally anywhere you can put an expression:

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

I would usually consider this a code smell though, but for quick debugging it can be handy.