Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OCaml: Leaving fields in records undefined?

Tags:

record

ocaml

I have this record type:

type syllable = {onset: consonant list; nucleus: vowel list; coda: consonant list};;

What if I want to instantiate a syllable where only the nucleus is defined? Can I give it a default value? Does it default to [] or something like that?

like image 576
Nick Heiner Avatar asked Sep 15 '09 03:09

Nick Heiner


3 Answers

Just to make newacct's answer clearer, here's an example

let default_syllable = { onset = []; nucleus = []; coda = [] }

let choose_only_nucleus nucleus =
   { default_syllable with nucleus = nucleus }
like image 178
zrr Avatar answered Nov 01 '22 02:11

zrr


No, I don't think you can leave things undefined. Uninitialized values cause all sorts of problems in languages like C and so it is avoided in OCaml. (Although there are a few functions in the standard library that leaves some things undefined, like String.create, I don't think you can do it yourself.)

You would have to either fill in all the fields yourself (and use the empty list [] or something like that for values you don't care about), or use a pre-existing value of this type and use the record update syntax to create a new record with the fields you care about changed, and the other ones copied over from the pre-existing record.

like image 27
newacct Avatar answered Nov 01 '22 03:11

newacct


I think it's a better idea to use "optional" fields.

type syllable = {onset: consonant list option; nucleus: vowel list option; coda: consonant list option};;

That way, you can define what you need.

{onset = Some [consonant, consonant, ...],
 nucleus = None,
 coda = Some [consonant, consonant, consonant, ...]}

I think that's the syntax.

like image 39
Michael Avatar answered Nov 01 '22 02:11

Michael