[clean-list] safe arithmetic operations
John van Groningen
johnvg@cs.kun.nl
Wed, 13 Nov 2002 16:23:45 +0100
Scott wrote:
>My wish list is : make the operations + and * truly safe.
I assume that with safe you mean that arithmetic overflows are detected.
This would break some existing programs and it would make programs slower.
I have implemented a module 'SafeInt' with +, - and * that detect overflows.
The code is included in this mesage (at the end). Compile this module first
before using it, because otherwise inlining will not work the first time.
>Clean should make a distinction between finite lists and infinite lists. But I think this is more difficult than my above wish.
Tail strict lists have already been implemented. It is probably possible to
prevent cycles in lists, but we currently don't plan to implement this.
Regards,
John van Groningen
implementation module SafeInt;
import StdMisc;
(+%) infixl 6 :: !Int !Int -> Int;
(+%) a b = code {
.inline +%
.newlocallabel l
addIo
jmp_false l
jmp e_SafeInt_sadd_overflow
:l
.end
}
(-%) infixl 6 :: !Int !Int -> Int;
(-%) a b = code {
.inline -%
.newlocallabel l
subIo
jmp_false l
jmp e_SafeInt_ssub_overflow
:l
.end
}
(*%) infixl 6 :: !Int !Int -> Int;
(*%) a b = code {
.inline *%
.newlocallabel l
mulIo
jmp_false l
jmp e_SafeInt_smul_overflow
:l
.end
}
add_overflow :: .a;
add_overflow = abort "+% overflow";
sub_overflow :: .a;
sub_overflow = abort "-% overflow";
mul_overflow :: .a;
mul_overflow = abort "*% overflow";
system module SafeInt;
(+%) infixl 6 :: !Int !Int -> Int;
(-%) infixl 6 :: !Int !Int -> Int;
(*%) infixl 6 :: !Int !Int -> Int;
add_overflow :: .a;
sub_overflow :: .a;
mul_overflow :: .a;