Version française
Home     About     Download     Resources     Contact us    
Browse thread
Interactive technical computing
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Jon Harrop <jon@f...>
Subject: Re: [Caml-list] F#
On Thursday 08 March 2007 02:12, Erik de Castro Lopo wrote:
> I'm mainly a Linux guy so the chances of me getting up close and personal
> with F# are exactly zero :-).

Actually the F# compiler and tools are freely available and run under Mono (on 
Linux). I've had a little play with C# from Mono and was really impressed, 
but I haven't tried F# from Mono yet.

> However, I am interested in hearing about 
> the differences between F# and Ocaml wrt operator overloading. Care to
> clue me (and everyone else) in?

I can try. Basically, overloading is very popular in languages like C++ and 
C#. Programmers even overload functions and constructors in those languages.

General overloading doesn't sit well with type inference because the code no 
longer conveys a sufficient amount of type information to resolve the 
overload and infer all of the types. So general overloading is bad for type 
inferred languages like F# and .NET APIs that use overloading make for uglier 
F# code that uses them.

However, operator overloading (i.e. overloading symbols) makes numerical code 
so much easier to read that it is worth sacrificing some inference for it.

The arithmetic operators default to int:

> let add a b = a + b;;
val add : int -> int -> int

So you keep OCaml compatibility. But the operators can be applied to floats:

> 1.1 + 2.2;;
val it : float = 3.3

SML provides the same capability up to this point but F# allows the 
overloading to be extended. It already works for vectors:

> let a = vector [1.; 2.; 3.] and b = vector [2.; 3.; 4.];;
val a : vector
val b : vector
> a + b;;
val it : vector = [3.; 5.; 7.]

and you can even extend it to work on your own types by augmenting the type 
constructor with static member functions:

> type expr =
    | Int of int
    | Add of expr * expr
    | Mul of expr * expr with
    static member ( + ) (f, g) = Add(f, g)
    static member ( * ) (f, g) = Mul(f, g)
  end;;

Then you can even use + to add symbolic expressions:

> Int 3 + Int 4;;
val it : expr = Int 3 + Int 4

However, the operator must always be statically resolved, so the code is 
always fast because it doesn't incur run-time dispatch.

That's the basic idea. There are some subtlties, like is the type of 
+ 'a->'a->'a or 'a->'b->'c?

-- 
Dr Jon D Harrop, Flying Frog Consultancy Ltd.
OCaml for Scientists
http://www.ffconsultancy.com/products/ocaml_for_scientists