OCaml学习——OCaml-Datatypes
OCaml Datatypes
We have seen a number of basic types (e.g. int, float, char, string, bool) and a few structured types (e.g. pairs, tuples, options, lists).
In this lecture, we will see some more general ways to define our own new types and data structures.
Type Abbreviations
1 |
|
- helpful documentation
- add nothing of substance to the language (equal to an existing type)
Data Types
1 |
|
|
means or, a value with type my_bool
is one of two things. Tru
and Fal
are called "constructors" (recall the constructors in Coq )
OCaml's datatype mechanism allows you to create types that contain precisely the values you want!
This is like an "enumeration" type in Pascal, C, Java,... . Just recall the explanation of constructors and constructor expressions in Coq this datatype(definition) explicitly enumerate a finite set of elements.
Data Types Can Carry Additional Values
Test
1 |
|
Summary
A datatype \(t\) has constructors \(c_1\) \(c_2\) \(c_3\) \(\cdots\)
Each constructor may carry a value (like Square(s)) or be a constant constructor (like Green)
We build values of type \(t\) by applying constructors to values (or by applying constant constructors to nothing)
We examine values of type t by pattern-matching
Inductive Datatypes
Recall using int to represent nat, not good.
1 |
|
Recall in Coq. Induction Zero (O) and Succ of nat (S(n:nat)).
1 |
|
Summary
OCaml data types: a powerful mechanism for defining comples data structures.
- precise
- general
- type checker helps you detect errors
本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!