摆脱“厄运金字塔".在F#中 [英] Getting rid of the "pyramid of doom" in F#
本文介绍了摆脱“厄运金字塔".在F#中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我将几个口头表达打包成一个函数:
I have several verbal expressions that I've packaged into one function:
open FsVerbalExpressions
open FsVerbalExpressions.VerbalExpression
open System.Text.RegularExpressions
open System
let createOrVerbExFromList (verbExList: VerbEx list) =
let orVerbEx =
verbExList
|> List.reduce (fun acc thing -> verbExOrVerbEx RegexOptions.IgnoreCase acc thing) //simpleVerbEx
orVerbEx
let k12VerbEx =
let kTo12 = ["SCHOOL"; "DIST"; "SD"; "HS"; "BD OF ED"]
kTo12
|> List.map (fun word -> VerbEx(word))
|> createOrVerbExFromList
let twoYearCollegeVerbEx =
VerbEx("2 Year College")
let universityVerbEx =
VerbEx("UNIV")
let privateSchoolVerbEx =
VerbEx("ACAD")
//Here there be dragons:
let newInst (x: string) =
match (isMatch x k12VerbEx) with
| true -> "K - 12"
| _ -> match (isMatch x twoYearCollegeVerbEx) with
| true -> "2 Year College"
| _ -> match (isMatch x universityVerbEx) with
| true -> "University"
| _ -> match (isMatch x privateSchoolVerbEx) with
| true -> "Private / Charter School"
| _ -> "Other"
我想重写newInst
函数,使其不再是厄运金字塔".我的问题是如何摆脱厄运金字塔?我怀疑这将是某种async
工作流程或其他计算表达式,但对我来说这些都是非常.
I'd like to rewrite the newInst
function so that it's no longer the "pyramid of doom. My question is how can I get rid of the pyramid of doom? Can I get rid of it? I have the suspicion that it will be some sort of async
workflow or other computational expression, but those are all very new to me.
推荐答案
如果只匹配布尔值,则if ... elif
就足够了:
If you are only matching against booleans, then if ... elif
is sufficient:
let newInst (x: string) =
if isMatch x k12VerbEx then
"K - 12"
elif isMatch x twoYearCollegeVerbEx then
"2 Year College"
elif isMatch x universityVerbEx then
"University"
elif isMatch x privateSchoolVerbEx then
"Private / Charter School"
else
"Other"
更灵活的可能性是创建活动模式:
A more flexible possibility would be to create an active pattern:
let (|IsMatch|_|) f x =
if isMatch x f then Some () else None
let newInst (x: string) =
match x with
| IsMatch k12VerbEx -> "K - 12"
| IsMatch twoYearCollegeVerbEx -> "2 Year College"
| IsMatch universityVerbEx -> "University"
| IsMatch privateSchoolVerbEx -> "Private / Charter School"
| _ -> "Other"
这篇关于摆脱“厄运金字塔".在F#中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文