cue-lang / docs-and-content

A place to discuss, plan, and track documentation on cuelang.org
5 stars 1 forks source link

docs/howto/ensure-int-is-odd-or-even: Ensuring that an integer value is either odd or even #97

Closed jpluscplusm closed 3 months ago

jpluscplusm commented 3 months ago
exec cue eval -i file.cue
cmp stdout out
-- file.cue --
#even: num={2 * (__div(num, 2))}
#odd:  num={2*(__div(num, 2)) + 1}

a: 56 & #even
b: 97 & #even
c: 56 & #odd
d: 97 & #odd
-- out --
#even: 2 * div(num, 2)
#odd:  2*div(num, 2) + 1
a:     56
b:     _|_ // b: conflicting values 96 and 97
c:     _|_ // c: conflicting values 57 and 56
d:     97

Can, of course, be expanded to check for multiples of any integer, not just 2; but the resulting page title would get a little wordy.

This also works:

#even: math.Trunc(x/2) * 2

... but doing the same for #odd is more fiddly, as it requires responding to the sign of the original number. i.e. the trailing +1 needs to be -1 if the number is negative. Not /hard/, just inelegant, relative to the first solution, above.

jpluscplusm commented 3 months ago

It'd be worth checking in on https://github.com/cue-lang/cue/issues/2926 to see if a standard-library-based solution could also be demonstrated.

jpluscplusm commented 3 months ago

https://cuelang.org/cl/1177968

jpluscplusm commented 3 months ago

Closed via https://github.com/cue-lang/cuelang.org/commit/e57cd0ec72701eeb7c62621a14d53cd621f07737, and now published at https://alpha.cuelang.org/docs/howto/validate-integer-value-parity/.

Many thanks for writing this, @noamtd!