Possible frequent problem (and solution): using Js.Option.map


#1

From a discussion on discord; put here because I suspect it is a common question.

This code doesn’t work:

let x: option(int) = Some(5);
let y: option(int) = Js.Option.map(x => x + 1, x);

The error message is: This expression should not be a function, the expected type is ('a -> 'b [@bs]), which is in OCaml syntax. In ReasonML, you do this to fix it:

let y: option(int) = Js.Option.map([@bs] x => x + 1, x);

There is a more up-to-date notation that also works:

let y: option(int) = Js.Option.map((. x) => x + 1, x);

From what I understand, the [@bs] makes it an uncurried function as per this page: https://bucklescript.github.io/docs/en/function.html (Why it has to be uncurried, I got no idea, but I am sure someone can explain it in a response here.)


#2

This is fixed in the latest bs-platform. As a rule of thumb, you should always be on the latest bs-platform; it’s a very stable package.

Also, use Belt.Option instead


#3

Hi @chenglou,

Is this the autogenerated documentation for Belt.Option? https://bucklescript.github.io/bucklescript/api/Belt.Option.html

Some of these functions can be guessed at but is there any other site with more documentation and possible code examples? I guess we can try to figure out by reading the code https://github.com/BuckleScript/bucklescript/blob/master/jscomp/others/belt_Option.ml (which is actually quite simple in this module) but assume Belt is so new that more detailed docs remain a TODO item?

Thanks!


#4

Yeah, the docs are quite sparse. Sorry about that. I have some plans to flesh out the docs, just trying to find time :sweat_smile:

In the meantime you can get a nice overview of Belt overall at https://bucklescript.github.io/bucklescript/api/Belt.html –it explains the overall ideas, conventions, motivations etc. Let us know if you get stuck anywhere, or if you have something you’re trying to do but not sure how to use Belt to do it, people in the Discord will be able to help out.


#5

No worries and no need to apologize… I understand it’s brand new and still labeled “beta”.

I’d be happy to help with some documentation PRs at some point but I’m still way too much of a newbie!

Actually having the best luck just reading code from public projects searching on Github at this point but it’s harder to find examples in the wild of some of the newer syntax/modules like Belt. Anyway, thanks for working on it really appreciate it!