or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

async-programming.mdcharacter-operations.mdcollections.mdconfiguration.mdcore-infrastructure.mddata-encoding.mddate-time.mdexternal-integration.mdindex.mdnumeric-types.mdreactive-programming.mdstring-operations.mdtype-system.md
tile.json

numeric-types.mddocs/

Numeric Types

Comprehensive numeric type system providing JavaScript implementations of .NET numeric types with full arithmetic operations, overflow handling, and precision control.

Long Module - 64-bit Integer Implementation

JavaScript implementation of 64-bit integers with complete arithmetic operations, supporting both signed and unsigned variants.

Long Class

Core 64-bit integer type with low/high 32-bit representation.

class Long {
    constructor(low: number, high: number, unsigned?: boolean);
    
    // Properties
    low: number;        // Low 32 bits
    high: number;       // High 32 bits
    unsigned: boolean;  // Whether unsigned
    
    // Core methods
    GetHashCode(): number;
    Equals(x: any): boolean;
    CompareTo(x: any): number;
    toString(radix?: number): string;
    toJSON(): string;
}

// Usage
import { Long } from "fable-library/Long.js";

const long1 = new Long(0x12345678, 0x9ABCDEF0, false);
console.log(long1.toString(16)); // Hex representation
console.log(long1.Equals(long1)); // true

Constants

Predefined Long constants for common values.

// Import constants
import { 
    ZERO, ONE, NEG_ONE, MAX_VALUE, MIN_VALUE,
    MAX_SAFE_INTEGER, MIN_SAFE_INTEGER,
    UZERO, UONE, MAX_UNSIGNED_VALUE
} from "fable-library/Long.js";

console.log(ZERO.toString()); // "0"
console.log(MAX_VALUE.toString()); // "9223372036854775807"
console.log(MAX_UNSIGNED_VALUE.toString()); // "18446744073709551615"

Arithmetic Operations

Complete set of arithmetic operations with overflow handling.

// Basic arithmetic
function add(left: Long, right: Long): Long;
function subtract(left: Long, right: Long): Long;
function multiply(left: Long, right: Long): Long;
function divide(left: Long, right: Long): Long;
function modulo(left: Long, right: Long): Long;
function negate(long: Long): Long;

// Usage
import { add, subtract, multiply, divide, fromString } from "fable-library/Long.js";

const a = fromString("1000000000000");
const b = fromString("2000000000000");

const sum = add(a, b);           // 3000000000000
const diff = subtract(b, a);     // 1000000000000
const product = multiply(a, b);  // 2000000000000000000000000
const quotient = divide(b, a);   // 2

console.log(sum.toString());      // "3000000000000"
console.log(quotient.toString()); // "2"

Bitwise Operations

Full bitwise operation support for bit manipulation.

// Bitwise operations
function and(left: Long, right: Long): Long;
function or(left: Long, right: Long): Long;
function xor(left: Long, right: Long): Long;
function not(long: Long): Long;

// Bit shifting
function shiftLeft(long: Long, numBits: number): Long;
function shiftRight(long: Long, numBits: number): Long;

// Usage
import { and, or, xor, not, shiftLeft, fromNumber } from "fable-library/Long.js";

const a = fromNumber(0xFF00);
const b = fromNumber(0x00FF);

const andResult = and(a, b);        // 0x0000
const orResult = or(a, b);          // 0xFFFF
const xorResult = xor(a, b);        // 0xFFFF
const notResult = not(a);           // Bitwise complement

const shifted = shiftLeft(a, 8);    // 0xFF0000

console.log(orResult.toString(16)); // "ffff"

Conversion Functions

Convert between Long and other numeric types.

// From other types
function fromNumber(value: number, unsigned?: boolean): Long;
function fromString(str: string, unsigned?: boolean, radix?: number): Long;
function fromBytes(bytes: number[], unsigned?: boolean, le?: boolean): Long;

// To other types
function toNumber(long: Long): number;
function toString(long: Long, radix?: number): string;
function toBytes(long: Long, le?: boolean): number[];

// Usage
import { fromNumber, fromString, toNumber, toString, toBytes } from "fable-library/Long.js";

// Create from different sources
const fromNum = fromNumber(12345);
const fromStr = fromString("9223372036854775807");
const fromHex = fromString("DEADBEEF", false, 16);
const fromBytes = fromBytes([0xEF, 0xBE, 0xAD, 0xDE], false, true);

// Convert to other types
console.log(toNumber(fromNum)); // 12345
console.log(toString(fromHex, 16)); // "deadbeef"
console.log(toBytes(fromNum, true)); // [57, 48, 0, 0, 0, 0, 0, 0]

Comparison Functions

Compare Long values with full ordering support.

// Equality and comparison
function equals(left: Long, right: Long): boolean;
function compare(left: Long, right: Long): number;

// Relational comparisons
function lessThan(left: Long, right: Long): boolean;
function lessThanOrEqual(left: Long, right: Long): boolean;
function greaterThan(left: Long, right: Long): boolean;
function greaterThanOrEqual(left: Long, right: Long): boolean;

// Usage
import { compare, lessThan, equals, fromString } from "fable-library/Long.js";

const a = fromString("1000000000000");
const b = fromString("2000000000000");

console.log(equals(a, a)); // true
console.log(lessThan(a, b)); // true
console.log(compare(a, b)); // -1
console.log(compare(b, a)); // 1
console.log(compare(a, a)); // 0

Utility Functions

Additional utility functions for Long operations.

// Type and state checking
function isLong(obj: any): boolean;
function isZero(long: Long): boolean;
function isNegative(long: Long): boolean;
function isPositive(long: Long): boolean;
function isOdd(long: Long): boolean;
function isEven(long: Long): boolean;

// Usage
import { isLong, isZero, isOdd, ZERO, ONE } from "fable-library/Long.js";

console.log(isLong(ZERO)); // true
console.log(isLong(42)); // false

console.log(isZero(ZERO)); // true
console.log(isOdd(ONE)); // true
console.log(isEven(ONE)); // false

Int32 Module - 32-bit Integer Operations

32-bit integer parsing and validation with .NET-compatible number styles.

Enums

enum NumberStyles {
    AllowHexSpecifier = 0x00000200
}

Functions

// Parse with validation
function tryParse(str: string, style?: NumberStyles, unsigned?: boolean, bitsize?: number): [boolean, number];

// Parse with exception on failure
function parse(str: string, style?: NumberStyles, unsigned?: boolean, bitsize?: number): number;

// Validate numeric value
function isValid(value: any, unsigned: boolean, bitsize: number): boolean;

// Usage
import { tryParse, parse, NumberStyles, isValid } from "fable-library/Int32.js";

// Safe parsing
const [success, value] = tryParse("123");
console.log(success, value); // true, 123

const [hexSuccess, hexValue] = tryParse("FF", NumberStyles.AllowHexSpecifier);
console.log(hexSuccess, hexValue); // true, 255

// Direct parsing (throws on failure)
try {
    const num = parse("456");
    console.log(num); // 456
    
    const hexNum = parse("ABC", NumberStyles.AllowHexSpecifier);
    console.log(hexNum); // 2748
} catch (e) {
    console.log("Parse failed");
}

// Validation
console.log(isValid(127, false, 8)); // true (fits in signed 8-bit)
console.log(isValid(256, true, 8));  // false (doesn't fit in unsigned 8-bit)

Double Module - Double-Precision Float Operations

Double-precision floating point parsing and validation.

Functions

// Parse with validation
function tryParse(str: string): [boolean, number];

// Parse with exception on failure
function parse(str: string): number;

// Check for infinity
function isInfinity(x: number): boolean;

// Usage
import { tryParse, parse, isInfinity } from "fable-library/Double.js";

// Safe parsing
const [success, value] = tryParse("123.456");
console.log(success, value); // true, 123.456

const [nanSuccess, nanValue] = tryParse("not a number");
console.log(nanSuccess, nanValue); // false, NaN

// Direct parsing
try {
    const num = parse("3.14159");
    console.log(num); // 3.14159
} catch (e) {
    console.log("Parse failed");
}

// Infinity checking
console.log(isInfinity(Infinity)); // true
console.log(isInfinity(-Infinity)); // true
console.log(isInfinity(123.45)); // false

Decimal Module - Decimal Number Implementation

High-precision decimal arithmetic using the big.js library for financial and scientific calculations.

Type Definition

// Decimal is implemented as a wrapper around Big from big.js
type Decimal = any; // Actually wraps Big instance

Creation and Conversion

// Create from components
function fromParts(low: number, mid: number, high: number, isNegative: boolean, scale: number): Decimal;

// Create from basic types
function fromNumber(n: number): Decimal;
function fromString(str: string): Decimal;

// Convert to basic types
function toNumber(x: Decimal): number;
function toString(x: Decimal): string;

// Usage
import { fromNumber, fromString, toNumber, toString } from "fable-library/Decimal.js";

// Create decimals
const dec1 = fromNumber(123.456);
const dec2 = fromString("789.012345");
const dec3 = fromString("999999999999999999999999.999999");

// Convert back
console.log(toNumber(dec1)); // 123.456
console.log(toString(dec2)); // "789.012345"
console.log(toString(dec3)); // "999999999999999999999999.999999"

Arithmetic Operations

Complete arithmetic operations with high precision.

// Basic arithmetic
function add(x: Decimal, y: Decimal): Decimal;
function subtract(x: Decimal, y: Decimal): Decimal;
function multiply(x: Decimal, y: Decimal): Decimal;
function divide(x: Decimal, y: Decimal): Decimal;
function remainder(x: Decimal, y: Decimal): Decimal;
function negate(x: Decimal): Decimal;

// Usage
import { 
    fromString, add, subtract, multiply, divide, 
    remainder, toString 
} from "fable-library/Decimal.js";

const a = fromString("123.456");
const b = fromString("78.9");

const sum = add(a, b);           // 202.356
const diff = subtract(a, b);     // 44.556
const product = multiply(a, b);  // 9740.6784
const quotient = divide(a, b);   // ~1.5647527...
const rem = remainder(a, b);     // Remainder

console.log(toString(sum));      // "202.356"
console.log(toString(product));  // "9740.6784"

Comparison Functions

// Equality and ordering
function equals(x: Decimal, y: Decimal): boolean;
function compare(x: Decimal, y: Decimal): number;

// Usage
import { equals, compare, fromString } from "fable-library/Decimal.js";

const a = fromString("123.456");
const b = fromString("123.456");
const c = fromString("789.012");

console.log(equals(a, b)); // true
console.log(equals(a, c)); // false

console.log(compare(a, c)); // -1 (a < c)
console.log(compare(c, a)); // 1  (c > a)
console.log(compare(a, b)); // 0  (a == b)

Mathematical Functions

// Mathematical operations
function abs(x: Decimal): Decimal;
function ceil(x: Decimal): Decimal;
function floor(x: Decimal): Decimal;
function round(x: Decimal, dp?: number): Decimal;
function truncate(x: Decimal): Decimal;

// Usage
import { 
    fromString, abs, ceil, floor, round, 
    truncate, toString 
} from "fable-library/Decimal.js";

const num = fromString("-123.789");

console.log(toString(abs(num)));       // "123.789"
console.log(toString(ceil(num)));      // "-123"
console.log(toString(floor(num)));     // "-124"
console.log(toString(round(num, 1)));  // "-123.8"
console.log(toString(truncate(num)));  // "-123"

const positive = fromString("123.789");
console.log(toString(ceil(positive)));  // "124"
console.log(toString(floor(positive))); // "123"

BigInt Module - Arbitrary Precision Integers

F# BigInteger implementation providing arbitrary precision integer arithmetic based on the F# BigInt library.

BigInteger Type Operations

The BigInteger type (from z.fsi) provides comprehensive arbitrary precision integer operations.

Arithmetic Operators

// Basic arithmetic operations
val (+) : BigInteger -> BigInteger -> BigInteger    // Addition
val (-) : BigInteger -> BigInteger -> BigInteger    // Subtraction  
val (*) : BigInteger -> BigInteger -> BigInteger    // Multiplication
val (/) : BigInteger -> BigInteger -> BigInteger    // Division
val (%) : BigInteger -> BigInteger -> BigInteger    // Modulus
val (~-) : BigInteger -> BigInteger                 // Negation
val (~+) : BigInteger -> BigInteger                 // Identity

// Usage in F#
let a = 123456789012345678901234567890I
let b = 987654321098765432109876543210I

let sum = a + b
let product = a * b
let quotient = b / a

Bitwise Operations

// Bitwise operations
val (>>>) : BigInteger -> int -> BigInteger         // Right shift
val (<<<) : BigInteger -> int -> BigInteger         // Left shift
val (&&&) : BigInteger -> BigInteger -> BigInteger  // Bitwise AND
val (|||) : BigInteger -> BigInteger -> BigInteger  // Bitwise OR
val (^^^) : BigInteger -> BigInteger -> BigInteger  // Bitwise XOR

// Usage in F#
let x = 0xFFFFFFFFFFFFFFFFI
let shifted = x >>> 8
let masked = x &&& 0xFF00I
let combined = x ||| 0x00FFI

Conversion Methods

// Convert to various numeric types
member ToSByte : sbyte
member ToByte : byte
member ToInt16 : int16
member ToUInt16 : uint16
member ToInt32 : int32
member ToUInt32 : uint32
member ToInt64 : int64
member ToUInt64 : uint64
member ToSingle : single
member ToDouble : double
member ToDecimal : decimal

// Usage
let big = 12345678901234567890I
let asInt = big.ToInt32    // May overflow
let asDouble = big.ToDouble
let asDecimal = big.ToDecimal

Static Methods

// Static utility methods
static member Parse : text:string -> BigInteger
static member DivRem : x:BigInteger * y:BigInteger -> BigInteger * BigInteger
static member GreatestCommonDivisor : x:BigInteger * y:BigInteger -> BigInteger
static member Pow : x:BigInteger * y:int32 -> BigInteger
static member Abs : x:BigInteger -> BigInteger

// Usage
let parsed = BigInteger.Parse("123456789012345678901234567890")
let (quotient, remainder) = BigInteger.DivRem(big1, big2)
let gcd = BigInteger.GreatestCommonDivisor(big1, big2)
let power = BigInteger.Pow(2I, 100)
let absolute = BigInteger.Abs(-123I)

Properties

// Instance properties
member Sign : int           // -1, 0, or 1
member IsZero : bool       // True if zero
member IsOne : bool        // True if one

// Static properties
static member Zero : BigInteger
static member One : BigInteger  
static member Two : BigInteger

// Usage
let big = -123I
printfn "%d" big.Sign      // -1
printfn "%b" big.IsZero    // false

let zero = BigInteger.Zero
let one = BigInteger.One
let two = BigInteger.Two

JavaScript Integration

When compiled to JavaScript, BigInteger operations are available through the generated modules:

// Import BigInteger functionality (conceptual - actual import depends on compilation)
import * as BigInt from "fable-library/BigInt.js";

// The F# BigInteger becomes JavaScript functions
// Exact API depends on Fable compilation output

Mathematical Examples

Factorial Calculation

// Calculate large factorials
let rec factorial n =
    if n <= 1I then 1I
    else n * factorial (n - 1I)

let fact100 = factorial 100I
// Result: 93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000

Fibonacci Sequence

// Generate large Fibonacci numbers
let rec fibonacci n =
    match n with
    | 0I -> 0I
    | 1I -> 1I
    | n -> fibonacci (n - 1I) + fibonacci (n - 2I)

// More efficient iterative version
let fibonacciIter n =
    let rec loop a b i =
        if i = n then a
        else loop b (a + b) (i + 1I)
    loop 0I 1I 0I

let fib1000 = fibonacciIter 1000I

Cryptographic Operations

// Modular exponentiation for RSA-like operations
let rec modPow baseNum exponent modulus =
    if exponent = 0I then 1I
    elif exponent % 2I = 0I then
        let half = modPow baseNum (exponent / 2I) modulus
        (half * half) % modulus
    else
        (baseNum * modPow baseNum (exponent - 1I) modulus) % modulus

// Example: 2^100 mod 97
let result = modPow 2I 100I 97I

Performance Considerations

Efficient Operations

// Use compound assignment when possible
let mutable accumulator = 0I
for i in 1I .. 1000I do
    accumulator <- accumulator + i    // Accumulate efficiently

// Prefer iterative over recursive for large operations
let sumRange start finish =
    let mutable sum = 0I
    let mutable current = start
    while current <= finish do
        sum <- sum + current
        current <- current + 1I
    sum

Memory Management

// BigInteger values are immutable, so intermediate values create garbage
// Consider algorithms that minimize intermediate allocations

// Less efficient - creates many intermediate BigInteger values
let rec powerSum base exp =
    if exp = 0I then 0I
    else (BigInteger.Pow(base, exp)) + powerSum base (exp - 1I)

// More efficient - reuses computation
let powerSumEfficient base exp =
    let mutable sum = 0I
    let mutable power = 1I
    for i in 0I .. exp do
        sum <- sum + power
        power <- power * base
    sum