Is it possible to do function overloading in F#?

我怕爱的太早我们不能终老 提交于 2019-12-05 19:42:04

问题


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!


回答1:


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)



回答2:


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'


来源:https://stackoverflow.com/questions/1936143/is-it-possible-to-do-function-overloading-in-f

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!