adambard / learnxinyminutes-docs

Code documentation written as code! How novel and totally my idea!
https://learnxinyminutes.com/
Other
11.46k stars 3.33k forks source link

Collection Instanciation Error : OCaml #5003

Open lokasku opened 2 months ago

lokasku commented 2 months ago

I noticed an error in the Records/A collection of values with named fields chapter when instantiating cow variable:

type animal = 
   {
      name: string;
      color: string;
      legs: int;
   }
;;

let cow = 
   {  name: "cow";
      color: "black and white";
      legs: 4; 
   }
;;
val cow : animal

cow.name ;;
- : string = "cow"

This should be replaced by

type animal = 
   {
      name: string;
      color: string;
      legs: int;
   }
;;

let cow = 
   {  name = "cow";
      color = "black and white";
      legs = 4; 
   }
;;

(*
val cow : animal

cow.name ;;
- : string = "cow"
*)
lokasku commented 2 months ago

It is also found at the end of the file; this error is present throughout the file where assignment is done with : instead of =.

(*** Mutability ***)

(* Records and variables are immutable: you cannot change where a variable points to *)

(* However, you can create mutable polymorphic fields *)
type counter = { mutable num : int } ;;

let c = { num: 0 } ;;
c.num ;; (* Gives 0 *)
c.num <- 1 ;; (* <- operator can set mutable record fields *)
c.num ;; (* Gives 1 *)

(* OCaml's standard library provides a ref type to make single field mutability easier *)
type 'a ref = { mutable contents : 'a } ;;
let counter = ref 0 ;;
!counter ;; (* ! operator returns x.contents *)
counter := !counter + 1 ;; (* := can be used to set contents *)