F# 中的全局运算符重载 [英] Global operator overloading in F#
问题描述
我正在开始为笛卡尔积和矩阵乘法定义自己的运算符.
I'm starting down the road of defining my own operators for Cartesian products and matrix multiplication.
矩阵和向量别名为列表:
With matrices and vectors aliased as lists:
type Matrix = float list list
type Vector = float list
我可以通过编写自己的初始化代码(并获得笛卡尔积)
I can write my own initialisation code (and get a Cartesian product into the bargain) by writing
let inline (*) X Y =
X |> List.collect (fun x -> Y |> List.map (fun y -> (x, y)))
let createVector size f =
[0..size - 1] |> List.map (fun i -> f i)
let createMatrix rows columns f =
[0..rows - 1] * [0..columns - 1] |> List.map (fun i j -> f i j)
到目前为止一切顺利.问题是我对 *
的定义消除了正常定义,即使我的版本只为列表定义,列表没有自己的乘法运算符.
So far so good. The problem is that my definition of *
wipes out the normal definition, even though my version is only defined for Lists, which don't have their own multiplication operator.
文档http://msdn.microsoft.com/en-us/library/vstudio/dd233204.aspx 声明新定义的运算符优先于内置运算符".然而,我没想到所有的数字化身都会被消灭——静态类型肯定会解决这个问题吗?
The documentation http://msdn.microsoft.com/en-us/library/vstudio/dd233204.aspx states that "newly defined operators take precedence over the built-in operators". However, I wasn't expecting all of the numerical incarnations to be wiped out -- surely static typing would take care of this?
我知道可以定义一个尊重类型的全局运算符,因为 MathNet Numerics 使用 *
进行矩阵乘法.我也想沿着这条路走下去,这需要打字系统将矩阵乘法优先于 Matrix
类型(它们本身就是列表)的笛卡尔积.
I know it is possible to define a global operator that respects types, because MathNet Numerics uses *
for matrix multiplication. I would also like to go down that road, which would require the typing system to prioritise matrix multiplication over the Cartesian product of Matrix
types (which are themselves lists).
有谁知道如何在 F# 中做到这一点?
Does anyone know how to do this in F#?
推荐答案
这是(非惯用的)解决方案:
Here is the (non idiomatic) solution:
type Mult = Mult with
static member inline ($) (Mult, v1: 'a list) = fun (v2: 'b list) ->
v1 |> List.collect (fun x -> v2 |> List.map (fun y -> (x, y))) : list<'a * 'b>
static member inline ($) (Mult, v1:'a ) = fun (v2:'a) -> v1 * v2 :'a
let inline (*) v1 v2 = (Mult $ v1) v2
这篇关于F# 中的全局运算符重载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!