From d9e25980d9b3e62e89ab731ed5fbc33126df57e6 Mon Sep 17 00:00:00 2001 From: Jim Pryor Date: Sun, 12 Dec 2010 01:48:14 -0500 Subject: [PATCH] translating: more about records Signed-off-by: Jim Pryor --- translating_between_OCaml_Scheme_and_Haskell.mdwn | 30 ++++++++++++++++++++++- 1 file changed, 29 insertions(+), 1 deletion(-) diff --git a/translating_between_OCaml_Scheme_and_Haskell.mdwn b/translating_between_OCaml_Scheme_and_Haskell.mdwn index 2e33b1a2..69ba76d4 100644 --- a/translating_between_OCaml_Scheme_and_Haskell.mdwn +++ b/translating_between_OCaml_Scheme_and_Haskell.mdwn @@ -385,7 +385,9 @@ We will however try to give some general advice about how to translate between O ##Records## -Haskell and OCaml both have `records`, which are essentially just tuples with a pretty interface. The syntax for declaring and using these is a little bit different in the two languages. +Haskell and OCaml both have `records`, which are essentially just tuples with a pretty interface. We introduced these in the wiki notes [here](/coroutines_and_aborts/). + +The syntax for declaring and using these is a little bit different in the two languages. * In Haskell one says: @@ -451,6 +453,32 @@ Haskell and OCaml both have `records`, which are essentially just tuples with a # makegray { red = 0; green = 127; blue = 255 };; - : color = {red = 0; green = 0; blue = 0} +* Records just give your types a pretty interface; they're entirely dispensable. Instead of: + + type color = { red : int; green : int; blue : int };; + let c = { red = 0; green = 127; blue = 255 };; + let r = c.red;; + + You could instead just use a more familiar data constructor: + + type color = Color of (int * int * int);; + let c = Color (0, 127, 255);; + + and then extract the field you want using pattern-matching: + + let Color(r,_,_) = c;; + (* or *) + match c with Color(r,_,_) -> ... + + (Or you could just use bare tuples, without the `Color` data constructor.) + + The record syntax only exists because programmers sometimes find it more convenient to say: + + ... c.red ... + + than to reach for those pattern-matching constructions. + + ##Functions## -- 2.11.0