F#中这种惯用的Option用法吗? [英] Is this usage of Option idiomatic in F#?
本文介绍了F#中这种惯用的Option用法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我具有以下功能,该功能检查数据源中customer
的存在并返回ID.这是使用Option
类型的正确/惯用方式吗?
I have the following function that checks the existance of a customer
in a data source and returns the id. Is this the right/idiomatic way of using the Option
type?
let findCustomerId fname lname email =
let (==) (a:string) (b:string) = a.ToLower() = b.ToLower()
let validFName name (cus:customer) = name == cus.firstname
let validLName name (cus:customer) = name == cus.lastname
let validEmail email (cus:customer) = email == cus.email
let allCustomers = Data.Customers()
let tryFind pred = allCustomers |> Seq.tryFind pred
tryFind (fun cus -> validFName fname cus && validEmail email cus && validLName lname cus)
|> function
| Some cus -> cus.id
| None -> tryFind (fun cus -> validFName fname cus && validEmail email cus)
|> function
| Some cus -> cus.id
| None -> tryFind (fun cus -> validEmail email cus)
|> function
| Some cus -> cus.id
| None -> createGuest() |> fun cus -> cus.id
推荐答案
当您缩进缩进时再好不过了,因此值得一看,看看您能对此做些什么.
It's never good when you have indent upon indent, so it'd be worthwhile seeing what you can do about it.
这是通过引入一些辅助功能来解决该问题的一种方法:
Here's one way to address the problem, by introducing a little helper function:
let tryFindNext pred = function
| Some x -> Some x
| None -> tryFind pred
您可以在findCustomerId
函数中使用它来展平后备选项:
You can use it inside the findCustomerId
function to flatten the fallback options:
let findCustomerId' fname lname email =
let (==) (a:string) (b:string) = a.ToLower() = b.ToLower()
let validFName name (cus:customer) = name == cus.firstname
let validLName name (cus:customer) = name == cus.lastname
let validEmail email (cus:customer) = email == cus.email
let allCustomers = Data.Customers()
let tryFind pred = allCustomers |> Seq.tryFind pred
let tryFindNext pred = function
| Some x -> Some x
| None -> tryFind pred
tryFind (fun cus -> validFName fname cus && validEmail email cus && validLName lname cus)
|> tryFindNext (fun cus -> validFName fname cus && validEmail email cus)
|> tryFindNext (fun cus -> validEmail email cus)
|> function | Some cus -> cus.id | None -> createGuest().id
这与此处概述的方法非常相似.
这篇关于F#中这种惯用的Option用法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文