Chapter 15. Data Types

WHAT'S IN THIS CHAPTER?

  • Understanding ambiguously defined data

  • Encapsulating state in types

  • Leveraging discriminated unions

  • Defining recursive data types

Specifying types is often thought of as merely a way to tell your computer how to handle the contents of some location in memory. However, as time has progressed, it has been discovered that data types actually can do much more. Beyond telling the compiler which operations to perform on binary data, types can provide a powerful way to label the conceptual meaning of your data. In effect, they become contracts about the semantic meaning of that data. Both data and functions labeled in this way are easier to reason about and can help to ensure the correctness of your code.

AMBIGUOUSLY TYPED DATA

A problem rife in current mainstream design methodologies is the frequent use of ambiguously typed data. A bool, a double, an exception and a null are all very general. They each carry no meaning other than that which is given to them by their surrounding context. The compiler can do nothing to check if your method inputs, and their internal uses are valid.

What is stopping you from passing a double that represents a probability into a method that wants a specific scalar measurement? Even NASA, with its legendary software QA, has experienced defects of this type. One of these failures has even caused the failure of a very expensive mission. You may be surprised to learn that null references and mishandled exceptions are exactly ...

Get Professional F# 2.0 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.