What are you trying to do can be done quite well using <i>type classes<i>. First-order type classes can be emulated in F# using interfaces. First write SimData as an interface type 'a SimData = interface abstract create : int -> 'a abstract binop : binop_t -> 'a -> 'a -> 'a -> int -> int -> unit // ... end F# already has some "type class" interfaces for numeric types in Microsoft.FSharp.Math.Types, in particular INumeric. Now it is possible to write a function that produces an instance of SimData given an instance of INumeric. E.g., let f (num : 'a INumeric) = { new ('a ref) SimData with create n = ref num.Zero and binop op r a b wa wb = r := match op with | B_add -> num.Add (!a, !b) // ... } Of course for your problem you need more operations than the INumeric type class defines (e.g., bitwise operations) so you could extend INumeric with a sub-interface that supports these operations. You can build instances of SimData like so (N.B. I think the typeof function is deprecated but fslib is still using it for this function getNumericAssociation) let getSimData () = getNumericAssociation (typeof () : 'a typ) |> Option.get |> f let simDataInt32 : (Int32 ref) SimData = getSimData () let simDataUInt64 : (UInt64 ref) SimData = getSimData ()

By on 9/26/2006 8:17 PM ()

Going back to the original code, the problem stems from the fact that overloaded operators are resolved statically in F#. That is,

1
2
3
4
5
6
7
8
 

let simDataSimpleType zero one = 
  let mask = ~~~ zero in 
  let sign_extend a w = if zero = (a &&& (one <<< (w-1))) then a ||| (mask <<< w) else a in
  (mask,sign_extend)  

does not give rise to a function that is generic over the type of integers used. This is why Greg passes in a dictionary of operations that represents the implementation of not only zero and one, but also all related operations such as <<< and &&&.

(nb. I've used the F# symbolic names for these operators since I find it many times clearer than the OCaml names, which we only recommend for use when cross-compiling F# code).

Don

By on 9/26/2006 11:03 PM ()

Thanks for the info.

Looking back at the manual I think it pretty much says what has been summerized here, though I must say I find it rather heavy going.

V. much looking forward to one of those f# books that are in the pipeline which I've no doubt will make all this much clearer.

Cheers,

Andy

By on 9/28/2006 6:07 AM ()
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