viva_math/vecn

N-dimensional vectors as List(Float).

Pure functional, no NIF, no broadcasting beyond scalar/vector. For heavy linear algebra, defer to viva_tensor.

Most functions return Result when shapes mismatch.

Types

pub type VecN =
  List(Float)

Values

pub fn add(
  a: List(Float),
  b: List(Float),
) -> Result(List(Float), Nil)

Element-wise add. Errors on length mismatch.

pub fn add_scalar(v: List(Float), s: Float) -> List(Float)
pub fn clamp(v: List(Float), lo: Float, hi: Float) -> List(Float)
pub fn cosine_similarity(
  a: List(Float),
  b: List(Float),
) -> Result(Float, Nil)

Cosine similarity: (a · b) / (‖a‖ · ‖b‖).

Returns Error(Nil) if either vector has zero length or lengths differ.

pub fn distance(
  a: List(Float),
  b: List(Float),
) -> Result(Float, Nil)
pub fn dot(a: List(Float), b: List(Float)) -> Result(Float, Nil)
pub fn euclidean_distance(
  a: List(Float),
  b: List(Float),
) -> Result(Float, Nil)

Euclidean (L₂) distance — alias for distance/2 for API parity with gleam_community_maths and downstream packages migrated off it.

pub fn length(v: List(Float)) -> Float

Length using progressive hypot reduction to avoid overflow.

pub fn length_squared(v: List(Float)) -> Float
pub fn lerp(
  a: List(Float),
  b: List(Float),
  t: Float,
) -> Result(List(Float), Nil)
pub fn lp_norm(v: List(Float), p: Float) -> Result(Float, Nil)

General Lₚ norm: (Σ |xᵢ|ᵖ)^(1/p).

Defined for p ≥ 1 (where it satisfies the triangle inequality and is a true norm). For 0 < p < 1 the formula still computes but the result is only a pseudo-norm (triangle inequality fails). The function does not reject 0 < p < 1 so callers can opt into the pseudo-norm regime.

Domain: p > 0 strictly. p ≤ 0 returns Error(Nil) because 1/p is undefined or infinite, and the underlying pow raises badarith on Erlang while returning Infinity on JavaScript — i.e. the behaviour would diverge across targets, which is unacceptable for a dual-target library.

Special cases: p = 2.0 collapses to Euclidean (length), p = 1.0 to Manhattan. Returns Ok(0.0) for the empty vector.

pub fn manhattan_distance(
  a: List(Float),
  b: List(Float),
) -> Result(Float, Nil)

Manhattan (L₁) distance: Σ |aᵢ − bᵢ|.

pub fn mean(v: List(Float)) -> Result(Float, Nil)
pub fn multiply(
  a: List(Float),
  b: List(Float),
) -> Result(List(Float), Nil)
pub fn negate(v: List(Float)) -> List(Float)
pub fn normalize(v: List(Float)) -> List(Float)
pub fn ones(n: Int) -> List(Float)
pub fn scale(v: List(Float), s: Float) -> List(Float)

Scalar multiplication.

pub fn splat(value: Float, n: Int) -> List(Float)
pub fn sub(
  a: List(Float),
  b: List(Float),
) -> Result(List(Float), Nil)
pub fn sum(v: List(Float)) -> Float
pub fn zeros(n: Int) -> List(Float)
pub fn zip_with(
  a: List(Float),
  b: List(Float),
  f: fn(Float, Float) -> Float,
) -> Result(List(Float), Nil)

Component-wise zip with a custom binary function.

Search Document