Define a primitive data type: Difference between revisions
Content added Content deleted
(add Ruby) |
(→Common Lisp: new example) |
||
Line 258: | Line 258: | ||
unsigned char value; // we don't need more space |
unsigned char value; // we don't need more space |
||
};</lang> |
};</lang> |
||
=={{header|Common Lisp}}== |
|||
The built-in integer type specifier provides range parameters. <code>deftype</code> may be used to define an alias for it. |
|||
<lang lisp>(deftype one-to-ten () |
|||
'(integer 1 10))</lang> |
|||
For a bounds check, one may use <code>typep</code> (a predicate) or <code>check-type</code> (signals an error if not of the type). |
|||
<lang lisp>(defun word (i) |
|||
(check-type i one-to-ten) |
|||
(case i |
|||
(1 "one") |
|||
(2 "two") |
|||
(3 "three") |
|||
(4 "four") |
|||
(5 "five") |
|||
(6 "six") |
|||
(7 "seven") |
|||
(8 "eight") |
|||
(9 "nine") |
|||
(10 "ten")))</lang> |
|||
(Note that the above can be written without the separate check-type by using <code>ecase</code> instead of <code>case</code>, which signals an error when no case matches.) |
|||
To inform the compiler that a variable will be of a certain type, permitting optimizations, use a declaration: |
|||
<lang lisp>(dolist (i numbers) |
|||
(declare (type one-to-ten i)) |
|||
...)</lang> |
|||
Note, however, that the standard does not specify what happens in the event that a declaration is false (though [[SBCL]], for example, does perform type checks on any declaration except when <code>safety</code> is 0); use <code>check-type</code> for portable bounds checks. |
|||
=={{header|E}}== |
=={{header|E}}== |