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
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 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 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 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ᵢ|.