SML List Odd Distribution

I have this bit of code:

fun foldr2(f, x::xs) = if xs = [] then x else f(x, foldr2(f, xs)) 

With type signature

 (''a * ''a -> ''a) * ''a list -> ''a 

It looks pretty straightforward, it performs a function that works on equality types and a list of equality types as arguments, due to the comparison xs = [] . However, for some reason, it works on input, such as (op +, [2.3, 2.7, 4.0]) , when in SML / NJ realities are not a type of equality. Can someone help me shed some light on why this magic happens?

+6
sml smlnj
source share
1 answer

I believe this is due to the magical way in which + overloaded for realities. For me, it almost comes down to being a compiler bug, although I would have to take a look at the definition of SML97 to determine exactly what the correct behavior should look like. Overloading + is a bit of a nasty dark corner in SML, IMHO.

For example, if you define a function of type real * real -> real and pass it as an argument to foldr2 , you get an expected error of the type:

 fun f (x : real * real) = 134.5 foldr2 (f, [1.4, 2.25, 7.0]) stdIn:8.1-8.29 Error: operator and operand don't agree [equality type required] 

You can even cause a type error by simply adding a type annotation to op + , which basically led me to the conclusion that this overload + causes a mysterious effect.

+2
source share

All Articles