Conditional pattern matching doesn't work

Hi,

I have some issue with the if syntax inside pattern matching branches.
For example, with the following code:

    let bytes = Belt.Array.makeBy(size.contents, index =>
      switch index {
      | i if i < length => msg->Js.String2.charCodeAt(i)->Belt.Int.fromFloat
      | i if i == length => 0x80
      | _ => 0x00
      }
    )

I got the following errors:

Syntax error!
  /home/emile/Projects/ocaml/website-catala/node_modules/rescript-hash/src/ReScriptHash/ReScriptHash_Sha384.res:142:10-12
  
  140 ┆ let bytes = Belt.Array.makeBy(size.contents, index =>
  141 ┆   switch index {
  142 ┆   | i if i < length => msg->Js.String2.charCodeAt(i)->Belt.Int.fromFl
        oat
  143 ┆   | i if i == length => 0x80
  144 ┆   | _ => 0x00
  
  Did you forget a `=>` here?


  Syntax error!
  /home/emile/Projects/ocaml/website-catala/node_modules/rescript-hash/src/ReScriptHash/ReScriptHash_Sha384.res:142:24-26
  
  140 ┆ let bytes = Belt.Array.makeBy(size.contents, index =>
  141 ┆   switch index {
  142 ┆   | i if i < length => msg->Js.String2.charCodeAt(i)->Belt.Int.fromFl
        oat
  143 ┆   | i if i == length => 0x80
  144 ┆   | _ => 0x00
  
  Did you forget a `{` here?

What am I doing wrong?

> rescript -v
9.1.4

Are you sure you are using ReScript >= 9.0.0 ?

Before that, the keyword for conditions in patterns was when. Your example compiles just fine in the playground, as long as you set the ReScript version to 9 or above on the settings tab.

Thanks for you answer!

Yes, as I mentionned in my post, I’m using ReScript 9.1.4.

both when and if keyword produces the same error…

The error messages are exactly the ones you’d get with ReScript < 9.0.0, that’s why @fham is asking. Just click here and change the settings to use ReScript 8.4.2, you’ll see!

It really feels like the binary that produces those error messages is not the same that is called when doing rescript -v.

Can you repro this from a new repo or even better from the playground?

2 Likes

What command are you using to run the build? And can you post your package.json file?

EDIT: just as a general tip, pattern match where the entire test is done in the if condition, while possible, doesn’t really make much sense. The biggest reason to use pattern matching is matching against the structure of the data. In this case you are not doing that. The code would be much clearer as:

let bytes = Belt.Array.makeBy(size.contents, index =>
  if index < length {
    msg->Js.String2.charCodeAt(i)->Belt.Int.fromFloat
  } else if index == length {
    0x80
  } else {
    0
  })
5 Likes

Indeed, I run the following command bsb -make-world -w -ws _. Anyway, I have:

> bsb -v
9.0.2

I agree with you, the code example is from the rescript-hash lib.

can you try doing this instead?

rescript build  -with-deps -w
1 Like