Functional programming F#嵌套记录 嵌套记录
记录是否类似于字典,它是一个有名称的对象树? 或记录只是简单类型的列表Functional programming F#嵌套记录 嵌套记录,functional-programming,f#,Functional Programming,F#,记录是否类似于字典,它是一个有名称的对象树? 或记录只是简单类型的列表 let r = { b = { a = 2 } } // is this possible? if not, how to achieve? is this useful in f#? 对我来说,有歧视的工会也有可能实现类似的行为(代码如下) 它有点像python或idk中的字典。下面的代码是伪代码 type Customer = { FirstName : string Con
let r = { b = { a = 2 } } // is this possible? if not, how to achieve? is this useful in f#?
对我来说,有歧视的工会也有可能实现类似的行为(代码如下)
它有点像python或idk中的字典。下面的代码是伪代码
type Customer =
{
FirstName : string
Contacts =
{
WorkPhone : string
MobilePhone : string
}
}
可以使用以下方法创建嵌套类型:
是的,您可以有嵌套的记录,但就像您的示例中的有区别的联合一样,您需要为嵌套类型指定一个名称:
type CustomerConracts =
{
WorkPhone : string
MobilePhone : string
}
type Customer =
{
FirstName : string
Contacts: CustomerConracts
}
let c = { FirstName = "John", Contacts = { WorkPhone = "123", Mobile phone = "098" } }
您可以在代码中看到一些模式,但记录与字典不同。您可以将它们看作具有强类型公共属性的类。如果需要创建字典,则必须使用一个可用的map/dictionary类或实现自己的类。例如,看看地图类型。
上面的代码显示您可以嵌套记录类型。除了使用@brianberns建议的匿名记录外,您还可以声明计划嵌套的数据类型。您可以使用匿名记录,因此实际上不必命名嵌套类型。
type Customer =
{
FirstName : string
Contacts :
{|
WorkPhone : string
MobilePhone : string
|}
}
let customer =
{
FirstName = "John"
Contacts =
{|
WorkPhone = "123-456-7890"
MobilePhone = "234-567-8901"
|}
}
type CustomerConracts =
{
WorkPhone : string
MobilePhone : string
}
type Customer =
{
FirstName : string
Contacts: CustomerConracts
}
let c = { FirstName = "John", Contacts = { WorkPhone = "123", Mobile phone = "098" } }
type Contact =
{
WorkPhone : string
MobilePhone : string
}
type Customer =
{
FirstName : string
Contacts : Contact
}
let cust : Customer =
{
FirstName = "Joe"
Contacts = { WorkPhone="1800131313"; MobilePhone="0863331311" }
}