Unsigned integer subtraction

Problem

You want to perform subtraction where the result is unsigned and never negative.

Solution

When a subtraction result would be negative, the answer should be zero. The following query creates a UDF that performs the calculation:

Copied!
({
  name: "subtract_unsigned",
  body: (
    (
      ["a", "b"],
      (
        {
          diff: (("a"), ("b")),
          negative: ((("diff"), (("diff"))))
        },
        (("negative"), 0, ("diff"))
      )
    )
  )
})
Query metrics:
  •    bytesIn:  296

  •   bytesOut:  398

  • computeOps:    1

  •    readOps:    0

  •   writeOps:    1

  •  readBytes:   30

  • writeBytes:  504

  •  queryTime: 37ms

  •    retries:    0

The following query calls the UDF with parameters that return a positive result:

Copied!
("subtract_unsigned", 123, 45)
78
Query metrics:
  •    bytesIn:  49

  •   bytesOut:  15

  • computeOps:   1

  •    readOps:   0

  •   writeOps:   0

  •  readBytes:   0

  • writeBytes:   0

  •  queryTime: 9ms

  •    retries:   0

The following query calls the UDF with parameters that return what would have been a negative result:

Copied!
("subtract_unsigned", 45, 123)
0
Query metrics:
  •    bytesIn:  49

  •   bytesOut:  14

  • computeOps:   1

  •    readOps:   0

  •   writeOps:   0

  •  readBytes:   0

  • writeBytes:   0

  •  queryTime: 2ms

  •    retries:   0

More information

Is this article helpful? 

Tell Fauna how the article can be improved:
Visit Fauna's forums or email docs@fauna.com

Thank you for your feedback!