I can't tell if this is a bug (since the numeric values differ) or not (since the semantics of compare just depend on whether the output is positive, negative, or zero). I believe that the explanation can be found in section 8.15.6.1 of the spec, which indicates that for known types a faster comparison function may be used in place of the generic function.

By on 11/17/2010 7:54 AM ()

I just checked the documentation for IComparable<T>:

Less than zero

This object is less than the object specified by the CompareTo method.

Zero

This object is equal to the method parameter.

Greater than zero

This object is greater than the method parameter.

So it looks like CompareTo() is not required to return -1, 0, 1. In the first case, you are comparing the individual chars 'z', 'b', 'c'. In the second case, you are comparing strings "z", "b", and "c". Apparently the implementation of CompareTo() is different for these types so technically your code is working correctly, but this seems kind of inconsistent (at least to me).

By on 11/17/2010 7:46 AM ()

I take back what I just wrote. I verified that the type of ca in foo1 is System.Char, not string. I based my reply on the fact that

compare 'a' 'c'

and

compare "a" "c"

give different results. Now I'm really confused.

By on 11/17/2010 7:58 AM ()

Hi Soot

I think your are pointing in the right direction. With the risk of just restating your post, I typed this into FSI:

1
2
3
4
5
6
7
8
9
let f = compare
let fc1 (c1: char) (c2: char) = compare c1 c2
let fc2: char -> char -> int = f
let fg1 c1 c2 = compare c1 c2
let fg2a: 'a -> 'a -> int = f
let fg2b: char -> char -> int = fg1 ;;
 
(f 'z' 'a', fc1 'z' 'a', fc2 'z' 'a',
 fg1 'z' 'a', fg2a 'z' 'a', fg2b 'z' 'a') ;;

I get these signatures deduced by FSI:

1
2
3
4
5
6
val f : ('a -> 'a -> int) when 'a : comparison
val fc1 : char -> char -> int
val fc2 : (char -> char -> int)
val fg1 : 'a -> 'a -> int when 'a : comparison
val fg2a : ('a -> 'a -> int) when 'a : comparison
val fg2b : (char -> char -> int)

and this result:

1
val it : int * int * int * int * int * int = (25, 1, 25, 1, 25, 1)

best regards
Robert

By on 11/17/2010 12:16 PM ()

Indeed, see also

1
2
    compare 'a' 'd'
    compare ('a' :> System.IComparable) ('d' :> System.IComparable)
By on 11/17/2010 12:18 PM ()
IntelliFactory Offices Copyright (c) 2011-2012 IntelliFactory. All rights reserved.
Home | Products | Consulting | Trainings | Blogs | Jobs | Contact Us | Terms of Use | Privacy Policy | Cookie Policy
Built with WebSharper