I would like to express something like the following:
if b then
let value = ... in
else
let value = .... in
let double = value * 2
But it seems that Ocaml does not allow this syntax. If I don't want to repeat the let double = value * 2
part, do I have to define value
as a reference?
Thank you very much!
Your trouble is that you're thinking of this imperatively (conditionally assign to a variable) rather than functionally (bind a name to the result of an expression):
let value = if b then ... else ... in
let double = value * 2
as mentioned, a functional approach is usually preferable.
However there can be scenarios where you want to use ocaml's imperative features:
let value = ref 2;;
begin
if 1=2 then
value := 4
else
value := 3
end;
let double = !value * 2
Note that one needs to ensure that the type of the expression in the if-branch and in the else-branch needs to be same -- here unit --, otherwise the compiler complains (of course).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With