Skip to content

Instantly share code, notes, and snippets.

@pigoz
Created November 1, 2017 12:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pigoz/dafa6240e8b3c9bb85988aa827070548 to your computer and use it in GitHub Desktop.
Save pigoz/dafa6240e8b3c9bb85988aa827070548 to your computer and use it in GitHub Desktop.
type a = { x: string };
type b = { x: int };
type c = { y: string };
type d = A | B(int);
type some_union =
| A(a)
| B(b)
| C(c)
| D(d);
/* i costruttori sono necessari per poter passare il tipo come props,
la tipizzazione non è strutturale appena si tirano in mezzo type
constructors
esempio del chiamante:
ReactDOMRe.renderToElementWithId(<App msg={App.make_da()}/>, "index");
*/
let make_a = (x) => A({ x: x });
let make_b = (x) => B({ x: x });
let make_c = (x) => C({ y: x });
let make_da = () => D(A);
let make_db = () => D(B(1));
/* inferisce da solo union -> string */
let getMsg = (msg) => {
switch msg {
| A(a) => a.x
| B(b) => string_of_int(b.x)
| C(c) => c.y
/* è magia nera: riesce a disambiguare i type constructor e sa che questo
A non prende nessun parametro, ed è diverso dall'A di some_union. Se si
toglie B(_) => viene fatto check di esaustività... es:
Warning number 8
/Users/pigoz/dev/save-edit/src/app.re 30:13-32:5
28 │ | B(b) => string_of_int(b.x)
29 │ | C(c) => c.y
30 │ | D(d) => switch d {
31 │ | A => "D.A"
32 │ }
33 │ };
34 │ };
You forgot to handle a possible value here, for example:
B _
*/
| D(d) => switch d {
| A => "D.A"
| B(_) => "D.B"
}
};
};
let component = ReasonReact.statelessComponent("App");
let handleClick = (_event, _self) => Js.log("clicked!");
let make = (~msg : some_union, _children) => {
...component,
render: (self) =>
<div onClick=(self.handle(handleClick))>
(ReasonReact.stringToElement(getMsg(msg)))
</div>
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment