[Haskell-cafe] numerical subtyping

Keean Schupke k.schupke at imperial.ac.uk
Wed Dec 8 06:11:44 EST 2004

You can also do this in a way that statically guarantees the property...

First you need to lift the numeric argument to the type level... This is 
for a double than an integer, but not impossible... First convert the 
double to
a pair of Integers (an infintite precision rational number)... Then each 
can be represented as a uniary number (this is the simplest but you will 
run out
of context reduction stack on any kind of real number, so binary or 
decimal representation
is better). The definitions required for this are in the attached library.

class Rat x -- class of type level rationals
instance (Number x,Number x) => Rat (x,x)

Now the specific class:

class Rat0to1 r
instance Div x y Zero => Rat0to1 (x,y) -- gives range 0.0000 -> 0.9999
instance (Div x y (Suc Zero),Mod x y Zero) => Rat0to1 (x,y) -- gives 
1.0000 -> 1.0000

an exmaple function applying the constraint:

rat0to1 :: Rat0to1 => r -> r
rat0to1 = id

The constraint can be converted from a static constraint to a runtime 
by using existentials:

data Ext0to1 = forall x y . (Number x,Number y,Rat0to1 (x,y)) => Ext0to1 


Derek Elkins wrote:

>>Is there a standard Haskell trick for checking run-time assignment to 
>>data types? I'd like a data type of Probability that ensures its
>>Double argument is between 0 and 1.

-------------- next part --------------
A non-text attachment was scrubbed...
Name: nat.tar.gz
Type: application/x-gzip
Size: 5419 bytes
Desc: not available
Url : http://www.haskell.org//pipermail/haskell-cafe/attachments/20041208/20a857c9/nat.tar.bin

More information about the Haskell-Cafe mailing list