This shows you the differences between two versions of the page.
dss:laboratoare:06 [2019/07/01 14:40] eduard.staniloiu [Mixins] |
dss:laboratoare:06 [2019/07/01 15:29] (current) eduard.staniloiu [Exercises] |
||
---|---|---|---|
Line 241: | Line 241: | ||
Specifying predicates as strings was used more commonly before the lambda syntax was added to D. Although string predicates as in this example are still used in Phobos, the **=>** lambda syntax may be more suitable in most cases. | Specifying predicates as strings was used more commonly before the lambda syntax was added to D. Although string predicates as in this example are still used in Phobos, the **=>** lambda syntax may be more suitable in most cases. | ||
</note> | </note> | ||
+ | |||
+ | ==== Exercises ==== | ||
+ | |||
+ | === 1. checkedint === | ||
+ | |||
+ | We want to define a **struct CheckedInt** that defines facilities for efficient checking of integral operations against overflow, casting with loss of precision, unexpected change of sign, etc. **CheckedInt** must work with both built-in integral types and other **CheckedInt**s. | ||
+ | |||
+ | CheckedInt offers encapsulated integral wrappers that do all checking internally and have configurable behavior upon erroneous results. For example, **CheckedInt!int** is a type that behaves like int but aborts execution immediately whenever involved in an operation that produces the arithmetically wrong result. | ||
+ | |||
+ | The declaration should look something like | ||
+ | <code d> | ||
+ | struct Checked(T, Hook) | ||
+ | </code> | ||
+ | |||
+ | In order to work with built-in types, you need to define: opAssign, opBinary, opBinaryRight, opCast, opCmp, opEquals, opOpAssign, opUnary. | ||
+ | |||
+ | CheckedInt has customizable behavior with the help of a second type parameter, Hook. Depending on the Hook type, core operations on the underlying integral may be verified for overflow or completely redefined. Implement the following predefined hooks: | ||
+ | - **Abort** : fails every incorrect operation with a message to std.stdio. stderr followed by a call to assert(0). It is the default second parameter, i.e. Checked!short is the same as Checked!(short, Abort). | ||
+ | - **Throw** : fails every incorrect operation by throwing an exception. | ||
+ | - **Warn**: prints incorrect operations to std.stdio.stderr but otherwise preserves the built-in behavior. | ||
+ | |||
+ | |||
+ | |||
+ |