F#中的重载+运算符 [英] Overloading + operator in F#

查看:83
本文介绍了F#中的重载+运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有这个:

open System
open System.Linq
open Microsoft.FSharp.Collections
type Microsoft.FSharp.Collections.List<'a> with
    static member (+) (First : List<'a>) (Second : List<'a>) =
        First.Concat(Second)

let a = [1; 2; 3; 4; 54; 9]
let b = [3; 5; 6; 4; 54]


for x in List.(+) a b do
    Console.WriteLine(x)

我想将最后一行转换为

for x in a + b do
    Console.WriteLine(x)

但是这样做可以给我一个

The type 'int list' does not support any operands named '+'

网络上的文档和示例都是胡言乱语的,尽管我使用了google-fu,但我仍然无法使其正常工作.基本上,来自python背景,我想像过去那样简洁地获取列表操作语法:infix表示法中的字符数不应超过1个.

解决方案

首先,重写运算符应以元组形式而不是携带形式声明.就您而言:

type Microsoft.FSharp.Collections.List<'a> with
    static member (+) (first: List<'a>, second: List<'a>) =
        first.Concat(second)

第二,解决此问题后,编译器将引发"Extension members cannot provide operator overloads. Consider defining the operator as part of the type definition instead."警告. F#中的重载运算符:(/)中已经对一些解决方法进行了详细讨论. /p>

So i have this:

open System
open System.Linq
open Microsoft.FSharp.Collections
type Microsoft.FSharp.Collections.List<'a> with
    static member (+) (First : List<'a>) (Second : List<'a>) =
        First.Concat(Second)

let a = [1; 2; 3; 4; 54; 9]
let b = [3; 5; 6; 4; 54]


for x in List.(+) a b do
    Console.WriteLine(x)

and I want to convert the last line into

for x in a + b do
    Console.WriteLine(x)

but doing so gives me a

The type 'int list' does not support any operands named '+'

The documentation and examples on the web are flakey, and despite my google-fu i have been unable to get it to work. Basically, coming from a python background, I want to get my list manipulation syntax as terse as I am used to: it should not need more than 1 character in infix notation.

解决方案

First, overriding operators should be declared in the tuple form, not in the carried form. In your case:

type Microsoft.FSharp.Collections.List<'a> with
    static member (+) (first: List<'a>, second: List<'a>) =
        first.Concat(second)

Second, after you fix that, the compiler raises the "Extension members cannot provide operator overloads. Consider defining the operator as part of the type definition instead." warning. There are some workarounds which have been discussed thoroughly in Overload operator in F#: (/).

这篇关于F#中的重载+运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆