首页 > 解决方案 > 展开单个案例联合“就地”

问题描述

我有一段漂亮的 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}

可以写这个不同的吗,我可以把奶酪拆开吗?

标签: f#

解决方案


我花了一些时间来弄清楚你的类型定义可能是什么。我得到了你的代码来编译以下内容,所以我假设这就是你所拥有的:

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 }

推荐阅读