Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Collection Instanciation Error : OCaml #5003

Open
lokasku opened this issue Jul 19, 2024 · 1 comment
Open

Collection Instanciation Error : OCaml #5003

lokasku opened this issue Jul 19, 2024 · 1 comment

Comments

@lokasku
Copy link

lokasku commented Jul 19, 2024

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
Copy link
Author

lokasku commented Jul 19, 2024

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant