F# 中的重载运算符:(/) [英] Overload operator in F#: (/)

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

问题描述

我想在 F# 中为字符串重载 (/) 运算符并保​​留数字的含义.

I would like to overload the (/) operator in F# for strings and preserve the meaning for numbers.

/// Combines to path strings
let (/) path1 path2 = Path.Combine(path1,path2)

let x = 3 / 4 // doesn't compile

如果我尝试以下操作,我会得到警告 29 扩展成员不能提供运算符重载.请考虑将运算符定义为类型定义的一部分."

If I try the following I get "Warning 29 Extension members cannot provide operator overloads. Consider defining the operator as part of the type definition instead."

/// Combines to path strings
type System.String with
  static member (/) (path1,path2) = Path.Combine(path1,path2)

有什么想法吗?

问候,叉

推荐答案

您不能为现有类型提供重载运算符.一种选择是使用另一个运营商名称(如 Natahan 建议的那样).但是,您也可以定义一个新类型来表示 F# 代码中的路径,并为此类型提供 / 运算符:

You cannot provide overloaded operators for existing types. One option is to use another operator name (as Natahan suggests). However, you can also define a new type to represent paths in your F# code and provide the / operator for this type:

open System    

// Simple type for representing paths
type Path(p) =
  // Returns the path as a string
  member x.Path = p 
  // Combines two paths
  static member ( / )(p1:Path, p2:Path) = 
    Path(IO.Path.Combine(p1.Path, p2.Path))

let n = 4 / 2
let p = Path("C:\") / Path("Temp")

这有一个重要的好处 - 通过使类型更加明确,您可以为类型检查器提供更多可用于验证您的代码的信息.如果您使用字符串来表示路径,那么您很容易将路径与其他字符串(例如名称)混淆.如果你定义你的 Path 类型,类型检查器将防止你犯这个错误.

This has one important benefit - by making the types more explicit, you give the type checker more information that it can use to verify your code. If you use strings to represent paths, then you can easily confuse path with some other string (e.g. name). If you define your Path type, the type-checker will prevent you from making this mistake.

此外,编译器不会允许您(简单地)错误地组合路径(如果您将路径表示为字符串,这很容易发生),因为 p + p 未定义(您可以使用只有 /,它正确使用了 Path.Combine).

Moreover, the compiler won't allow you to (simply) combine paths incorrectly (which can easily happen if you represent paths as strings), because p + p is not defined (you can use only /, which correctly uses Path.Combine).

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

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