Ocaml how to access elements in type definitions

The ocaml specifies the following type definition:

type yearday = YMD of int * int * int 

      

how would you refer to different types of type? For example, if I just want the value of the first int.

+3


source to share


1 answer


Portions of meaning like this are obtained through pattern matching. Here's a function that returns the first int:

let y_of_ymd (YMD (y, _, _)) = y

      

This is how it looks at the top (OCaml REPL):

# let y_of_ymd (YMD (y, _, _)) = y;;
val y_of_ymd : yearday -> int = <fun>
# let myymd = YMD (2017, 4, 18);;
val myymd : yearday = YMD (2017, 4, 18)
# y_of_ymd myymd;;
- : int = 2017
#

      



Update

If you have multiple choices in your type, you can use match

to determine what type of value is present

type yearday = YMD of int * int * int | YD of int * int

let y_of_yearday yearday =
    match yearday with
    | YMD (y, _, _) -> y
    | YD (y, _) -> y

      

There are more succinct ways to write this, but I think it gives a better idea of ​​what's going on.

+5


source







All Articles