F# 高阶属性访问器 [英] F# Higher-order property accessors

查看:28
本文介绍了F# 高阶属性访问器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚将原型元组升级为记录.有一天它可能会成为一个真正的类.同时,我想翻译这样的代码:

I just upgraded my prototyping tuple to a record. Someday it may become a real class. In the meantime, I want to translate code like this:

type Example = int * int
let examples = [(1,2); (3,4); (5,6)]
let descs = Seq.map (fst >> sprintf "%d") examples

为此:

type Example = {
  Field1 : int
  Field2 : int
  Description : string
}
let examples = [{Field1 = 1; Field2 = 2; Description = "foo"}
                {Field1 = 3; Field2 = 4; Description = "bar"}
                {Field1 = 5; Field2 = 6; Description = "baz"}]
let descs = Seq.map Description examples

问题是我希望得到一个函数 Description : Example ->string 当我声明 Example 记录时,但我没有.我已经探索了一些并尝试了类的属性,但这也不起作用.我是否只是缺少文档中的某些内容,还是必须手动编写高阶访问器?(这是我现在使用的解决方法.)

The problem is that I expected to get a function Description : Example -> string when I declared the Example record, but I don't. I've poked around a little and tried properties on classes, but that doesn't work either. Am I just missing something in the documentation or will I have to write higher-order accessors manually? (That's the workaround I'm using now.)

推荐答案

我同意在 F# 中以某种方式使用实例成员作为函数值会很好(无需显式构造 lambda 函数).这实际上已在 F# 社区中讨论过几次.这是一个相关链接:

I agree it would be nice to have some way of using instance member as a function value in F# (without explicitly constructing the lambda function). This has been actually discussed a few times in the F# community. Here is one related link:

该讨论中的一些建议选项是:

A few suggested options from that discussion are:

// This would turn '_' automatically into a lambda parameter
// (this looks okay in simple cases, but doesn't probably scale well)
examples |> Seq.map (_.Description)

// You would specify instance member using special '#' symbol
examples |> Seq.map (Example#Description)

所以,F# 团队已经意识到了这一点,但我不认为就这是否真的是那么重要的功能以及支持它的最佳方式有任何结论.

So, this is something that the F# team is aware of, but I don't think there is any conclusion whether this is actually that important feature and what would be the best way to support it.

这篇关于F# 高阶属性访问器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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