将无转换为0(F#)

时间:2014-04-02 20:08:07

标签: f#

此表达式正确评估为225.58:

let alfki = ctx.``[dbo].[Customers]``.Individuals.ALFKI
let changeNoneToZero x = match x with | Some v -> v | None -> 0m
let freights = alfki.FK_Orders_Customers |> Seq.map (fun x -> changeNoneToZero x.Freight) |> Seq.sum

对应于以下数据库查询:

select SUM(freight)
from dbo.Orders
where CustomerID = (
 select CustomerID from Customers
 where CustomerID = 'ALFKI')

是否存在changeNoneToZero函数的内置等效或近似模拟?我可以寻求Seq.sumBy代替吗?

2 个答案:

答案 0 :(得分:4)

@ ildjarn使用Seq.choose的方法。不是将None转换为0m然后对所有内容求和,而是仅选择那些不是None并将它们输入Seq.sum的值:

let freights = alfki.FK_Orders_Customers 
    |> Seq.choose (fun x -> x.Freight) 
    |> Seq.sum

谢谢@ildjarn!

答案 1 :(得分:2)

您还可以使用Option.fold

alfki.FK_Orders_Customers |> Option.fold (fun _ a -> a) 0m

你可以把它变成通用的:

let inline valOrZero ov = ov |> Option.fold (fun _ a -> a) LanguagePrimitives.GenericZero