F#记录:危险,仅用于有限用途或功能完备的吗? [英] F# Records: Dangerous, only for limited use, or well used functionality?

查看:70
本文介绍了F#记录:危险,仅用于有限用途或功能完备的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此已经在我的F#旅程中记录下来了,起初它们似乎很危险.乍一看,这似乎很聪明:

So have gotten to record in my F# journey and at first they seem rather dangerous. At first this seemed clever:

type Card = { Name  : string;
          Phone : string;
          Ok    : bool }

let cardA = { Name = "Alf" ; Phone = "(206) 555-0157" ; Ok = false }

cardA与Card匹配的想法.更不用说这里的简化模式匹配了:

The idea that the cardA is patten matched with Card. Not to mention the simplified pattern matching here:

let withTrueOk =
  list 
  |> Seq.filter
    (function 
      | { Ok = true} -> true
      | _ -> false
  )

问题是:

type Card = { Name  : string;
          Phone : string;
          Ok    : bool }

type CardTwo = { Name  : string;
          Phone : string;
          Ok    : bool }

let cardA = { Name = "Alf" ; Phone = "(206) 555-0157" ; Ok = false }

cardA现在是CardTwo类型,我想这与F#按顺序运行所有程序有关.

cardA is now of CardTwo type which I am guessing has to do with F# running everything in order.

现在这可能是不可能的情况,因为可能永远不会有相同的签名采用两种类型的机会,但这是有可能的.

Now this might be an impossible situation since there may never be a chance of the same signature taking on two type, but it is a possibility.

录制的东西用途有限吗?还是我只是在想一想呢?

Is recording something that has only limited use or am I just over thinking this one?

推荐答案

它们并不危险,并且不仅限于有限的用途.

They are not dangerous and they are not only for limited use.

我认为很少有两个类型具有相同的成员.但是,如果确实遇到这种情况,则可以限定要使用的记录类型:

I think it's very rare that you would have two types with the same members. But if you do encounter that situation, you can qualify the record type you want to use:

let cardA = { Card.Name = "Alf" ; Phone = "(206) 555-0157" ; Ok = false }

记录对于创建(主要是)不可变的数据结构非常有用.而且,只需更改一些字段即可轻松创建副本这一事实也很重要:

Records are very useful for creating (mostly) immutable data structures. And the fact that you can easily create a copy with just some fields changed is great too:

let cardB = { cardA with Ok = true }

这篇关于F#记录:危险,仅用于有限用途或功能完备的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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