Understanding Data Types and Subtypes

Sep 22, 2024

Notes on Data Types and Subtypes

Introduction to Subtypes

  • Creating subtypes can be complex and requires careful design.

Date as a Subtype

  • Definition of Date: Represented as a string (e.g., "4th June", "31st January").
    • Limitations of String Representation:
      • Cannot perform comparisons (e.g., less than, greater than).
      • Cannot perform arithmetic operations (e.g., adding days).

Proposed Solution for Date Representation

  • Convert date into an integer representing the day of the year.

    • Example:
      • January 1 = 0
      • January 31 = 30
      • February 1 = 31
      • Last day of a normal year = 364
      • Last day of a leap year = 365
  • Benefits:

    • Allows for integer operations like addition, subtraction, and comparisons.
    • Enables printing in a conventional format (e.g., converting integers back to date strings).

Operations on Dates

  • Define operations like:
    • print(int) to convert integer back to string (date).
    • Addition, subtraction, and comparison of dates.

Fractional Marks as a Subtype

  • Issue with Fractional Marks:
    • Example: Marks like 62.5 should be stored accurately without losing information.
    • Storing as integers can lead to loss of precision (rounding errors).

Proposed Solution for Marks Representation

  • Use float data type to represent real numbers.
    • Allows for complex real numbers and large/small values.
  • Alternative Solution:
    • Multiply fractional marks by 100 (to convert to integer).
    • Example: 62.5 becomes 6250.

Operations on Marks

  • Define operations:
    • print(int) to convert back to fractional format.
    • Allow addition, subtraction, and comparison of marks.

Handling Amounts and Prices

  • Example of Price Representation:
    • Prices often have two decimal places (e.g., 27.50).
  • Convert to integer by multiplying by 100 (2750).
  • Operations:
    • Addition, subtraction, and comparison of amounts.
    • Print function to display the value in currency format.

Handling Quantity

  • Quantities can be:
    • Whole numbers (e.g., 3 cans).
    • Fractional quantities (e.g., 1.25 kilos).
  • Multiply fractional quantities by 100 to store as an integer (e.g., 1.25 becomes 125).
  • Operations:
    • Addition, subtraction, and comparison of quantities.
    • Print function to display the value in correct format.

Conclusion

  • Designing subtypes for data types like dates, marks, amounts, and quantities is essential for efficient data handling and operations.