Search code examples
option-typereasonbucklescript

ReasonML, side effecting call on x if option is Some(x)


I have let intervalId = option(Js.Global.intervalId)

I would like a succinct way to do the side effecting call to Js.Global.clearInterval if the option has a value (ie. is Some(id) and not None)

Maybe the Belt.Option.map function is the answer, but I'm having problems putting it to use.

I'm very new to OCaml and ReasonML, but several languages I know have suitable functions. I'm paraphrasing some of them here to give the idea what I'm looking for:

In Scala I would say: intervalId.foreach(Js.Global.clearInterval)

In Swift I would say: intervalId.map(Js.Global.clearInterval)


Solution

  • Belt.Option.map(intervalId, Js.Global.clearInterval) should work fine, except it returns a value that you need to discard in some way to avoid a type error or warning.

    The safest way to discard values you don't need is to assign it to the wildcard pattern and include a type annotation to ensure the value you discard is what you expect it to be:

    let _: option(unit) = Belt.Option.map(intervalId, Js.Global.clearInterval)
    

    You can also use the ignore function, which works particularly well at the end of a sequence of pipes, but beware that you might then accidentally partially apply a function and discard it without actually executing the function and invoking the side-effect.

    intervalId
      |> Belt.Option.map(_, Js.Global.clearInterval)
      |> ignore