J_code
J_code

Reputation: 347

Initialize variable OCaml

How does one do the equivalent of int variable; in OCaml? That is, how does one simply declare a variable? According to the OCaml manual, it seems as if one can only declare and initialize a variable in one step. If so, why would that be desired behavior?

Upvotes: 1

Views: 4123

Answers (2)

kenlukas
kenlukas

Reputation: 3973

TL;DR

Simply put: you don't need to declare the types of your functions and variables, because OCaml will just figure them out for you! let x = 3;;

OCaml uses type inference which means your compiler infers your variable type by what you're assigning to it.

Type inference is the ability to automatically deduce, either partially or fully, the type of an expression at compile time. The compiler is often able to infer the type of a variable or the type signature of a function, without explicit type annotations having been given. In many cases, it is possible to omit type annotations from a program completely if the type inference system is robust enough, or the program or language is simple enough.

It's used because it takes the housekeeping out of variable creation. You don't need to explicitly call out what is obvious and the compiler takes care of it for you. Additionally, you need to better understanding of how your code is using the variables you're assigning. This article has a bit more detail

Upvotes: 1

PatJ
PatJ

Reputation: 6144

Variables in OCaml are declared and immutable.

The main reason for that is that uninitialized variables are a source of mistakes:

int x; // not initialized
read_and_use(x); // error

By making sure that your variables are always initialized, you can make sure that no unauthorized value can happen anywhere in your code.

The other point of this is immutability (that comes with declarative statements):

let x = 4;; (* Declare x *)
let f y = x + y;; (* Use x *)
let x = 5;; (* Declare a new variable with the same name as x *)
assert (f 10 = 14);; (* The x = 4 definition is used, as x is immutable *)

Since variables are constants, declaring them initialized would create constantly invalid variables. And that's pretty useless.

The fact that variables in OCaml (and most functional languages) are set once and only once may seem odd at first, but it actually doesn't change your language expressiveness and helps make your code clear and safe.

Upvotes: 2

Related Questions