2017-01-25 16 views
4

我有一個基於http post模板的azure函數。我把json從1道擴大到3.使用F#進行多個字段驗證(在天藍色的函數內)

let versionJ = json.["version"] 
let customerIdJ = json.["customerId"] 
let stationIdJ = json.["stationId"] 
match isNull versionJ with 

什麼是檢查所有三個空值的最佳方法?使用鬱金香?

match isNull versionJ, isNull customerIdJ, isNull stationIdJ with 

回答

2

這取決於你想要確切地檢查什麼。 如果你想看到至少有1空,那麼你就可以做到以下幾點:

let allAreNotNull = [versionJ; customerIdJ; stationIdJ] 
        |> List.map (not << isNull) 
        |> List.fold (&&) true 

如果要檢查所有的人都空,你可以做到以下幾點:

let allAreNull = [versionJ; customerIdJ; stationIdJ] 
       |> List.map isNull 
       |> List.fold (&&) true 

更新

你也可以用List.forall替換爲:

[versionJ; customerIdJ; stationIdJ] 
|> List.forall (not << isNull) 


[versionJ; customerIdJ; stationIdJ] 
|> List.forall isNull 
+0

當你想使用列表(哪個線程使用比簡單if更多的資源)。有更簡單的解決方案: – mjpolak

2

在這種情況下,我認爲使用簡單,如果將清潔液, 如果你定義isNull爲:

let inline isNull value = (value = null) 

然後就去做:

if isNull versionJ && isNull customerIdJ && isNull stationIdJ then 
    // your code 
2

另一種方法受到應用程序的啓發,如果所有元素(<>) null都適用createRecord

let createRecord v c s = v, c, s 

let inline ap v f = 
    match f, v with 
    | _  , null 
    | None , _  -> None 
    | Some f, v  -> f v |> Some 

let v = 
    Some createRecord 
    |> ap json.["version"] 
    |> ap json.["customerId"] 
    |> ap json.["stationId"]