Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assign a value based on a condition in Ocaml?

Tags:

ocaml

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!

like image 311
SoftTimur Avatar asked Dec 06 '22 20:12

SoftTimur


2 Answers

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
like image 90
Chuck Avatar answered Dec 26 '22 13:12

Chuck


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).

like image 28
ndbd Avatar answered Dec 26 '22 12:12

ndbd