P. Gillich
P. Gillich

Reputation: 289

Trouble understanding why this OCaml snippet won't compile

I'm new to OCaml and functional programming in general, and I'm struggling with the syntax. I find it difficult to write programs, since it seems to me that I'll write what I understand to be essentially the same code, but on the one hand one snippet compiles and runs with no issue but the other doesn't.

Here's one such case:

let foo () = 
     let x = ref 0 in !x
;;

val foo : unit -> int = <fun>

Compiles without a problem. My understanding of the above snippet is that when we call foo, we bind x to a reference to a memory cell storing 0, and then dereference x.

Now this snippet:

let seed = ref 6;;

let show_ref () = 
  let seed:=!seed+1 in !seed
;;

won't compile, and I don't understand why. It seems to me we do essentially the same thing here; we create a binding seed to a reference to memory cell containing the value 6. Then, we create a function that increments the thing stored in the cell referenced by seed, and then we dereference seed.

It's probably because I'm missing something basic, but I don't understand why the first thing was fine and the other was not fine. Could someone help me figure out what's really going on here?

Thanks!

Upvotes: 0

Views: 45

Answers (1)

Jeffrey Scofield
Jeffrey Scofield

Reputation: 66818

There is an OCaml language construct:

let name = expression1 in expression2

There is no OCaml language construct:

let name := expression1 in expression2

One way to look at this is that = is not an operator in the first case. It's just part of the syntax of let. This means you can't replace it by an arbitrary other operator as you are trying to do.

For completeness, here's how to write your second function:

let show_ref () =
    seed := !seed + 1;
    !seed

Note that in this code = is not an operator. But !, :=, and + are operators. You could define other symbols for these three operations (though you need to be careful of precedence). But you can't define a different symbol to use instead of = in a let expression.

Upvotes: 1

Related Questions