Ocaml how to access elements in type definitions
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 to share