4

I have an azure function based on the http post template. I expanded the json from 1 prop to 3.

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

What is the best way to check for null across all three? Use a tulple?

match isNull versionJ, isNull customerIdJ, isNull stationIdJ with
Jamie Dixon
  • 4,204
  • 4
  • 25
  • 47

3 Answers3

2

In this case, I think using simple if would be cleaners solution, if you have defined isNull as:

let inline isNull value = (value = null)

then just do:

if isNull versionJ && isNull customerIdJ && isNull stationIdJ then
    // your code
mjpolak
  • 721
  • 6
  • 24
2

It depends on what do you want to check for exactly. If you want to see that there is at least 1 null, then you can do the following:

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

If you want to check that all of them are nulls you can do the following:

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

update

You can also replace it with List.forall:

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


[versionJ; customerIdJ; stationIdJ]
|> List.forall isNull
derwasp
  • 802
  • 8
  • 17
  • When you want to use List(which lead do use more resources than simple if). There are simpler solutions: – mjpolak Jan 25 '17 at 20:32
2

Another approach is being inspired by Applicatives that apply createRecord if all elements (<>) null.

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"]