You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

F#模式匹配中`MyType2 list`与`MyType1 list->MyType2 list`类型不匹配问题

问题根源

F# 函数默认采用柯里化设计,标准库的List.map<'T,'U>签名为 ('T -> 'U) -> 'T list -> 'U list,你仅传入了第一个参数(类型转换函数),没有传入待处理的集合参数,因此返回值是一个等待接收MyType1 list输入的函数,类型为MyType1 list -> MyType2 list,和第一个分支返回的MyType2 list类型不匹配,并不是需要“强制触发执行”的问题,补全调用参数即可解决。
另外注意你的输入参数addOns是数组类型MyType1 [],无法直接作为List.map的输入参数,需要先做类型转换,或者直接使用适配数组的Array.map方法。

修正方案

方案1:补全List.map参数,适配输入数组类型

let private addOnsFromDto (addOns: MyType1 []) = 
    let typedList  = List.empty<MyType2>
    match addOns with
        | null -> typedList
        | _ -> addOns |> Array.toList |> List.map (fun a -> MyType2.create a.Prop1 a.Prop2)

方案2:简化写法,用Array.map提升性能

如果不需要保留中间变量可以直接简化代码,写法更简洁:

let private addOnsFromDto (addOns: MyType1 []) = 
    match addOns with
    | null -> []
    | _ -> addOns |> Array.map (fun a -> MyType2.create a.Prop1 a.Prop2) |> List.ofArray

内容的提问来源于stack exchange,提问作者Matt Austin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 23:24:03