liveBook · Manning

Unchecked-multiply

As explained in Clojure: The Essential Reference

unchecked-multiply-int is a Clojure function that multiplies two numeric values as primitive 32-bit signed integers without overflow checking.

`unchecked-multiply` multiplies exactly two numeric arguments without checking for integer overflow. Its result type follows numeric type promotion, so it is not necessarily an `int`. Use it when overflow is intentional, such as in integer-based hashing. section 5.13

Basic multiplication

`(unchecked-multiply 10 3)` returns `30`. Unlike ordinary arithmetic operators, `unchecked-multiply` does not accept more than two arguments. section 5.13

For specifically 32-bit signed integer arithmetic, use `unchecked-multiply-int` instead. It takes two numeric arguments within the `int` range, casts them to primitive `int`, and returns an `int` result that wraps on overflow. By contrast, `unchecked-multiply` can retain a more precise result type according to its operands. section 5.14 section 5.13

(defn scramble [^long x ^long y]                  ; #1
 (unchecked-add (unchecked-multiply 31 x) y))     ; #2

(defn hash-str [s]                                ; #3
  (let [large-prime 1125899906842597]             ; #4
    (reduce scramble large-prime (map int s))))   ; #5

(hash-str "couple words")                         ; #6
;; 1664082230529263278

(hash-str "even longer sentences")
;; -7674745620208396614

A string-hashing example combines `unchecked-multiply` with `unchecked-add` to make overflowing arithmetic part of the calculation. section 5.13

How Clojure: The Essential Reference covers it

How deep it goes
Defines two-argument behavior, overflow policy, and result typing, then contrasts the 32-bit `int` variant.
Examples
Shows a basic multiplication result and a string-hashing function that combines unchecked multiplication with addition.
What it assumes
Builds on basic arithmetic operators while defining unchecked arity and distinguishing promoted results from primitive `int` results.
What you can do after
Build it from scratch: use unchecked multiplication in a string hash, choosing the `int` variant when 32-bit results are required.
How it connects
Connects to numeric type promotion, integer overflow, hashing, `unchecked-add`, and primitive `int` arithmetic.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Clojure: The Essential Reference. The section links point to the parts of the book it draws on.