Skip to content

Instantly share code, notes, and snippets.

@dtchepak
Last active August 29, 2015 14:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dtchepak/3a55579e30131a6372b2 to your computer and use it in GitHub Desktop.
Save dtchepak/3a55579e30131a6372b2 to your computer and use it in GitHub Desktop.
// Based on http://www.nut-cracker.com.ar/index.php/overloading-in-f
type IVec<'T> =
abstract member Add : 'T -> 'T
abstract member Inv : unit -> 'T
type Vector2D = Vector2D of float * float with
interface IVec<Vector2D> with
member x.Add (Vector2D(b1, b2)) = match x with Vector2D(a1,a2) -> Vector2D(a1+b1, a2+b2)
member x.Inv () = match x with Vector2D(a1, a2) -> Vector2D(-a1, -a2)
type Vector3D = Vector3D of float * float * float with
interface IVec<Vector3D> with
member x.Add (Vector3D(b1, b2, b3)) = match x with Vector3D(a1,a2,a3) -> Vector3D(a1+b1, a2+b2, a3+b3)
member x.Inv () = match x with Vector3D(a1, a2, a3) -> Vector3D(-a1, -a2, -a3)
let addVec (x:IVec<'a>) y = x.Add(y)
let subVec (x:IVec<'a>) (y:IVec<'a>) = addVec x (y.Inv());;
(*
> addVec (Vector2D (1.,2.)) (Vector2D (3.,4.));;
val it : Vector2D = Vector2D (4.0,6.0)
> addVec (Vector2D (1.,2.)) (Vector3D (3.,4.,5.));;
addVec (Vector2D (1.,2.)) (Vector3D (3.,4.,5.));;
---------------------------^^^^^^^^^^^^^^^^^^^
stdin(17,28): error FS0001: This expression was expected to have type
Vector2D
but here has type
Vector3D
> addVec (Vector3D (1.,2.,3.)) (Vector3D (3.,4.,5.));;
val it : Vector3D = Vector3D (4.0,6.0,8.0)
*)
@gusty
Copy link

gusty commented Nov 19, 2014

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment