user1993381
user1993381

Reputation: 179

Mutable Types in OCaml

I am writing a function that swaps the contents of two reference calls.

let swap (x : a ref) (y :'a ref) : unit =

where

type 'a ref = {mutable contents : 'a}

I do not know what approach to take in order to solve this. Do I use pattern matching?

This is my test case

let test () : bool = 
  let r1 = { contents = 5 } in
  let r2 = { contents = 6 } in
  let _ = swap r1 r2 in
  (6, 5) = (r1.contents, r2.contents)
;; 

run_test "Swap different" test

Upvotes: 1

Views: 1575

Answers (1)

rgrinberg
rgrinberg

Reputation: 9878

Does this work?

let swap x y = 
  let z = !x in
  x := !y;
  y := z

Note that := and ! are just normal functions like so:

let (:=) r x = r.contents <- x
let (!) {contents} = contents

If you want to use own your type definition then you can do:

let swap' x y = 
  let z = x.contents in
  x.contents <- y.contents;
  y.contents <- z

Finally, if you're using batteries then you can just use BatRef.swap as defined here: http://ocaml-batteries-team.github.com/batteries-included/hdoc2/BatRef.html

Upvotes: 3

Related Questions