How to resolve the algorithm Define a primitive data type step by step in the jq programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Define a primitive data type step by step in the jq programming language
Table of Contents
Problem Statement
Demonstrate how to define a type that behaves like an integer but has a lowest valid value of 1 and a highest valid value of 10. Include all bounds checking you need to write, or explain how the compiler or interpreter creates those bounds checks for you.
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Define a primitive data type step by step in the jq programming language
Source code in the jq programming language
def typeof:
if type == "object" and has("type") then .type else type end;
def pp:
if type == "object" and has("type") then "\(.type)::\(.value)"
else .
end;
def smallint(i): i as $i
| if (i|type) == "number" and i == (i|floor) and i > 0 and i < 11 then {"type": "smallint", "value": i}
else empty
end ;
# A convenience function to save typing:
def s(i): smallint(i);
# To convert from the pretty-print representation back to smallint:
def tosmallint:
if type == "string" and startswith("smallint::") then
split("::") | smallint( .[1] | tonumber )
else empty
end ;
def add(a;b): smallint(a.value + b.value);
def minus(a;b): smallint(a.value - b.value);
def times(a;b): smallint(a.value * b.value);
def mod(a;b): smallint(a.value % b.value);
def divide(a;b): smallint( (a.value / b.value) | floor );
s(1) < s(3) # => true
add( s(1); s(2)) | pp # "smallint::3"
add( s(6); s(6)) # (nothing)
You may also check:How to resolve the algorithm Digital root/Multiplicative digital root step by step in the Component Pascal programming language
You may also check:How to resolve the algorithm Sieve of Eratosthenes step by step in the FreeBASIC programming language
You may also check:How to resolve the algorithm Sorting algorithms/Gnome sort step by step in the JavaScript programming language
You may also check:How to resolve the algorithm Sleep step by step in the Visual Basic .NET programming language
You may also check:How to resolve the algorithm Empty string step by step in the AutoHotkey programming language