f# - 展开单个案例联合“就地”
问题描述
我有一段漂亮的 F# 代码,将 Pizza 映射到 PizzaModel:
type Cheese = Cheese of string
type Pizza
{
Name: string
Cheese: Cheese
}
type PizzaModel =
{
PizzaName : string
Cheese: string
Toppings: string
}
let mapPizza pizza =
let (Cheese c) = pizza.Cheese
{ PizzaName = pizza.Name; Cheese = c}
可以写这个不同的吗,我可以把奶酪拆开吗?
解决方案
我花了一些时间来弄清楚你的类型定义可能是什么。我得到了你的代码来编译以下内容,所以我假设这就是你所拥有的:
type Cheese = Cheese of bool
type CheesePizza = { PizzaName : string; Cheese : bool }
type Pizza = { Name : string; Cheese : Cheese}
我认为没有办法在函数的最后一行解开内联奶酪,但是您可以在第一行以某种模式解开名称和奶酪:
let mapPizza { Cheese = Cheese c; Name = name } =
{ PizzaName = name; Cheese = c}
此模式匹配参数并使用嵌套模式提取奶酪。
编辑另一种方法是修改Cheese
类型并添加一个允许您轻松访问包装值的成员。这可以很容易地完成:
type Cheese =
| Cheese of string
member x.Value = let (Cheese v) = x in v
现在您可以使用内联解开该值pizza.Cheese.Value
:
let mapPizza pizza =
{ PizzaName = pizza.Name; Cheese = pizza.Cheese.Value }
推荐阅读
- javascript - ':' 冒号在 JavaScript 的导入中有什么作用?
- arduino - 如何使用 EEPROM 将 Arduino 内存中保存的数字重新引入程序?
- postgresql - 为什么 postgres 不创建数据库?
- vb.net - 重新格式化 csv 文件
- python - Django 在数据库中添加或更新日期
- javascript - 如何从 CSS-Grid 布局中删除不需要的空白,同时保持网格结构
- php - 我想创建一个循环,收集 PHP 中每个数组的第一项和最后一项
- typescript - 重载签名、联合类型和“没有重载匹配此调用”错误
- c - 在函数开头声明变量有什么好处吗?
- wordpress - “GATSBY_CONCURRENT_DOWNLOAD”在 Windows 上未被识别为内部或外部命令