OCaml: leave fields in undefined entries?

I have this type of entry:

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

What if I want to create an instance of a syllable where only the kernel is defined? Can I give it a default value? By default, is this the value [] or something like that?

+4
source share
3 answers

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

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

This way you can determine what you need.

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

I think the syntax.

+1
source

Just to make newacct more understandable, here is an example

 let default_syllable = { onset = []; nucleus = []; coda = [] } let choose_only_nucleus nucleus = { default_syllable with nucleus = nucleus } 
+5
source

No, I donโ€™t think you can leave things undefined. Uninitialized values โ€‹โ€‹cause all sorts of problems in languages โ€‹โ€‹like C, so avoid this in OCaml. (Although there are several functions in the standard library that leave some things undefined, such as String.create , I donโ€™t think you can do it yourself.)

You will either have to fill in all the fields yourself (and use an empty list [] , or something similar for values โ€‹โ€‹that you donโ€™t need), or use a pre-existing value of this type and use write update syntax to create a new record with the fields that you interested, and others copied from a pre-existing record.

+3
source