Something like
就像是
let f x = log(x)
and later I can apply f to matrix, vector or a float.
然后我可以将f应用于矩阵,向量或浮点数。
I guess it is not possible since F# is strictly static typed. Any other patters to overcome this problem?
我想这是不可能的,因为F#是严格静态类型的。任何其他模式来克服这个问题?
Thanks!
谢谢!
2 个解决方案
#1
4
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
14
See my answer to this question:
看看我对这个问题的回答:
Functions with generic parameter types
具有通用参数类型的函数
Briefly:
简述:
- You can overload members of a class (but not let-bound functions)
- 你可以重载一个类的成员(但不是let-bound函数)
- You can use 'inline' and 'hat' types
- 您可以使用“内联”和“帽子”类型
- You can simulate Haskell type classes and explicitly pass dictionaries-of-methods
- 您可以模拟Haskell类型类并显式传递方法字典
- You can use do run-time type tests casting from 'obj'
- 您可以使用'obj'执行的运行时类型测试
#1
4
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
14
See my answer to this question:
看看我对这个问题的回答:
Functions with generic parameter types
具有通用参数类型的函数
Briefly:
简述:
- You can overload members of a class (but not let-bound functions)
- 你可以重载一个类的成员(但不是let-bound函数)
- You can use 'inline' and 'hat' types
- 您可以使用“内联”和“帽子”类型
- You can simulate Haskell type classes and explicitly pass dictionaries-of-methods
- 您可以模拟Haskell类型类并显式传递方法字典
- You can use do run-time type tests casting from 'obj'
- 您可以使用'obj'执行的运行时类型测试