我在C#中有一个功能,可以检查学生是否参加了他的所有考试:
public Tuple<bool, string> HasTakenAllExams (string parameters)
{
// get the collection from db based on built query
if (parameters.Contains("FullTime"))
{
if (collection.English == null) { return new Tuple<bool, string>(false, "Value of English is null"); }
if (collection.Maths == null) { return new Tuple<bool, string>(false, "Value of Maths is null"); }
if (collection.PE == null) { return new Tuple<bool, string>(false, "Value of PE is null"); }
}
if (collection.Biology == null) { return new Tuple<bool, string>(false, "Value of Biology is null"); }
return new Tuple<bool, string>(true, null);
}
我在F#中重写它看起来像那样:
let HasTakenAllExams parameters : (bool * string) =
// get the collection from db based on built query
let mutable someStringMessage = ""
let mutable someBooleanValue = true
if (parameters:string).Contains("FullTime") then
if collection.English == null then someStringMessage <- "Value of English is null"; someBooleanValue <- false
if collection.Maths == null then someStringMessage <- "Value of Maths is null"; someBooleanValue <- false
if collection.PE == null then someStringMessage <- "Value of PE is null"; someBooleanValue <- false
if collection.Biology == null then someStringMessage <- "Value of Biology is null"; someBooleanValue <- false
(someBooleanValue, someStringMessage)
我猜测嵌套的if语句不是&#34;最佳实践&#34;在函数式编程和模式匹配中是要走的路?
if (parameters:string).Contains("FullTime") then
match collection.English with
| null -> someStringMessage <- "Value of English is null"; someBooleanValue <- false
match collection.Maths with
| null -> someStringMessage <- "Value of Maths is null"; someBooleanValue <- false
match collection.PE with
| null -> someStringMessage <- "Value of PE is null"; someBooleanValue <- false
else
match collection.Biology with
| null -> someStringMessage <- "Value of Biology is null"; someBooleanValue <- false
有没有更好/更有效的方法来编写上面的代码?
答案 0 :(得分:4)
我会像这样编写模式匹配等效的C#函数(我缩写parameters
和collection
):
let hasTookExams (prams: string) =
match prams.Contains("FullTime"), coll.English, coll.Maths, coll.PE, coll.Biology with
| true, null, _, _, _ -> (false, "Value of English is null")
| true, _, null, _, _ -> (false, "Value of Maths is null")
| true, _, _, null, _ -> (false, "Value of PE is null")
| _, _, _, _, null -> (false, "Value of Biology is null")
| _ -> (true, null)