Yin Zhu
Yin Zhu

Reputation: 17119

Is it possible to do function overloading in F#?

Something like

let f x = log(x)

and later I can apply f to matrix, vector or a float.

I guess it is not possible since F# is strictly static typed. Any other patters to overcome this problem?

Thanks!

Upvotes: 10

Views: 7947

Answers (2)

Brian
Brian

Reputation: 118865

See my answer to this question:

Functions with generic parameter types

Briefly:

  • You can overload members of a class (but not let-bound functions)
  • You can use 'inline' and 'hat' types
  • You can simulate Haskell type classes and explicitly pass dictionaries-of-methods
  • You can use do run-time type tests casting from 'obj'

Upvotes: 14

ssp
ssp

Reputation: 1722

You can use operator overloading for types/classes:

type Fraction = 
  { n : int; d : int; }
  static member (+) (f1 : Fraction, f2 : Fraction) =
    { n = f1.n * f2.d + f2.n * f1.d; d = f1.d * f2.d }

or inlined functions:

> let inline fi a b = a+b;;
val inline fi :
   ^a ->  ^b ->  ^c when ( ^a or  ^b) : (static member ( + ) :  ^a *  ^b ->  ^c)

Upvotes: 6

Related Questions