<!-- <a style="font-size: 120%" href="https://www.udemy.com/course/common-lisp-programming/?couponCode=LISPY-XMAS2023" title="This course is under a paywall on the Udemy platform. Several videos are freely available so you can judge before diving in. vindarel is (I am) the main contributor to this Cookbook."> Discover our contributor's Lisp course with this Christmas coupon.</a> -->
📢 New videos: <ahref="https://www.youtube.com/watch?v=h_noB1sI_e8">web dev demo part 1</a>, <ahref="https://www.youtube.com/watch?v=xnwc7irnc8k">dynamic page with HTMX</a>, <ahref="https://www.youtube.com/watch?v=Zpn86AQRVN8">Weblocks demo</a>
📕 <ahref="index.html#download-in-epub">Get the EPUB and PDF</a>
</p>
<divid="content"
<p>Common Lisp has a complete and flexible type system and corresponding
tools to inspect, check and manipulate types. It allows creating
custom types, adding type declarations to variables and functions and
thus to get compile-time warnings and errors.</p>
<h2id="values-have-types-not-variables">Values Have Types, Not Variables</h2>
<p>Being different from some languages such as C/C++, variables in Lisp are just
<em>placeholders</em> for objects<supid="fnref:1"role="doc-noteref"><ahref="type.html#fn:1"class="footnote"rel="footnote">1</a></sup>. When you <ahref="http://www.lispworks.com/documentation/lw50/CLHS/Body/m_setf_.htm"><code>setf</code></a> a variable, an object
is “placed” in it. You can place another value to the same variable later, as
you wish.</p>
<p>This implies a fact that in Common Lisp <strong>objects have types</strong>, while
variables do not. This might be surprising at first if you come from a C/C++
<p>The function <ahref="http://www.lispworks.com/documentation/HyperSpec/Body/f_tp_of.htm"><code>type-of</code></a> returns the type of the given object. The
returned result is a <ahref="http://www.lispworks.com/documentation/lw51/CLHS/Body/04_bc.htm">type-specifier</a>. In this case the first
element is the type and the remaining part is extra information (lower and
upper bound) of that type. You can safely ignore it for now. Also remember
that integers in Lisp have no limit!</p>
<p>Now let’s try to <ahref="http://www.lispworks.com/documentation/lw50/CLHS/Body/m_setf_.htm"><code>setf</code></a> the variable:</p>
<p>You see, <code>type-of</code> returns a different result: <ahref="http://www.lispworks.com/documentation/lw70/CLHS/Body/t_smp_ar.htm"><code>simple-array</code></a>
of length 5 with contents of type <ahref="http://www.lispworks.com/documentation/lcl50/ics/ics-14.html"><code>character</code></a>. This is because
<code>*var*</code> is evaluated to string <code>"hello"</code> and the function <code>type-of</code> actually
returns the type of object <code>"hello"</code> instead of variable <code>*var*</code>.</p>
<h2id="type-hierarchy">Type Hierarchy</h2>
<p>The inheritance relationship of Lisp types consists a type graph and the root
<p>The function <ahref="http://www.lispworks.com/documentation/lw51/CLHS/Body/f_descri.htm"><code>describe</code></a> shows that the symbol <ahref="http://www.lispworks.com/documentation/lw71/CLHS/Body/t_intege.htm"><code>integer</code></a>
is a primitive type-specifier that has optional information lower bound and
upper bound. Meanwhile, it is a built-in class. But why?</p>
<p>Most common Lisp types are implemented as CLOS classes. Some types are simply
“wrappers” of other types. Each CLOS class maps to a corresponding type. In
Lisp types are referred to indirectly by the use of <ahref="http://www.lispworks.com/documentation/lw51/CLHS/Body/04_bc.htm"><code>type
specifiers</code></a>.</p>
<p>There are some differences between the function <ahref="http://www.lispworks.com/documentation/HyperSpec/Body/f_tp_of.htm"><code>type-of</code></a> and
<ahref="http://www.lispworks.com/documentation/HyperSpec/Body/f_clas_1.htm"><code>class-of</code></a>. The function <code>type-of</code> returns the type of a given
object in type specifier format while <code>class-of</code> returns the implementation
details.</p>
<pre><codeclass="language-lisp">* (type-of 1234)
(INTEGER 0 4611686018427387903)
* (class-of 1234)
#<BUILT-IN-CLASS COMMON-LISP:FIXNUM>
</code></pre>
<h2id="checking-types">Checking Types</h2>
<p>The function <ahref="http://www.lispworks.com/documentation/lw51/CLHS/Body/f_typep.htm"><code>typep</code></a> can be used to check if the first argument is of
the given type specified by the second argument.</p>
<p>The function <ahref="http://www.lispworks.com/documentation/lw71/CLHS/Body/f_subtpp.htm"><code>subtypep</code></a> can be used to inspect if a type inherits
from the another one. It returns 2 values:</p>
<ul>
<li><code>T, T</code> means first argument is sub-type of the second one.</li>
<li><code>NIL, T</code> means first argument is <em>not</em> sub-type of the second one.</li>
<li><code>NIL, NIL</code> means “not determined”.</li>
<p>You may refer to the <ahref="http://www.lispworks.com/documentation/lw51/CLHS/Body/04_bc.htm">CLHS page</a> for more information.</p>
<h2id="defining-new-types">Defining New Types</h2>
<p>You can use the macro <ahref="http://www.lispworks.com/documentation/lw51/CLHS/Body/m_deftp.htm"><code>deftype</code></a> to define a new type-specifier.</p>
<p>Its argument list can be understood as a direct mapping to elements of rest
part of a compound type specifier. They are defined as optional to allow
symbol type specifier.</p>
<p>Its body should be a macro checking whether given argument is of this type
(see <ahref="http://www.lispworks.com/documentation/lw70/CLHS/Body/m_defmac.htm"><code>defmacro</code></a>).</p>
<p>We can use <code>member</code> to define enum types, for example:</p>
<pre><codeclass="language-lisp">(deftype fruit () '(member :apple :orange :pear))
</code></pre>
<p>Now let us define a new data type. The data type should be a array with at
most 10 elements. Also each element should be a number smaller than 10. See
<h2id="run-time-type-checking">Run-time type Checking</h2>
<p>Common Lisp supports run-time type checking via the macro
<ahref="http://www.lispworks.com/documentation/HyperSpec/Body/m_check_.htm#check-type"><code>check-type</code></a>. It accepts a <ahref="http://www.lispworks.com/documentation/HyperSpec/Body/26_glo_p.htm#place"><code>place</code></a> and a type specifier
as arguments and signals an <ahref="http://www.lispworks.com/documentation/HyperSpec/Body/e_tp_err.htm#type-error"><code>type-error</code></a> if the contents of
; Debugger entered on #<SIMPLE-TYPE-ERROR expected-type: NUMBER datum: "Hello">
The value of ARG is "Hello", which is not of type NUMBER.
[Condition of type SIMPLE-TYPE-ERROR]
...
</code></pre>
<h2id="compile-time-type-checking">Compile-time type checking</h2>
<p>You may provide type information for variables, function arguments
etc via <ahref="http://www.lispworks.com/documentation/HyperSpec/Body/f_procla.htm"><code>proclaim</code></a>, <ahref="http://www.lispworks.com/documentation/HyperSpec/Body/m_declai.htm"><code>declaim</code></a> (at the toplevel) and <ahref="http://www.lispworks.com/documentation/HyperSpec/Body/s_declar.htm"><code>declare</code></a> (inside functions and macros).</p>
<p>However, similar to the <code>:type</code> slot
introduced in <ahref="clos.html">CLOS section</a>, the effects of type declarations are
undefined in Lisp standard and are implementation specific. So there is no
guarantee that the Lisp compiler will perform compile-time type checking.</p>
<p>However, it is possible, and SBCL is an implementation that does
thorough type checking.</p>
<p>Let’s recall first that Lisp already warns about simple type
warnings. The following function wrongly wants to concatenate a string
and a number. When we compile it, we get a type warning.</p>
; Constant 3 conflicts with its asserted type SEQUENCE.
; See also:
; The SBCL Manual, Node "Handling of Types"
</code></pre>
<p>The example is simple, but it already shows a capacity some other
languages don’t have, and it is actually useful during development ;)
Now, we’ll do better.</p>
<h3id="declaring-the-type-of-variables">Declaring the type of variables</h3>
<p>Use the macro <ahref="http://www.lispworks.com/documentation/HyperSpec/Body/m_declai.htm"><code>declaim</code></a> with a <code>type</code> declaration identifier (other identifiers are “ftype, inline, notinline, optimize…).</p>
<p>Let’s declare that our global variable <code>*name*</code> is a string. You can
<p>For portable code, we would add run-time checks with an <code>assert</code>.</p>
<h3id="declaring-class-slots-types">Declaring class slots types</h3>
<p>A class slot accepts a <code>:type</code> slot option. It is however generally
<em>not</em> used to check the type of the initform. SBCL, starting with
<ahref="http://www.sbcl.org/all-news.html#1.5.9">version 1.5.9</a> released on
november 2019, now gives those warnings, meaning that this:</p>
<pre><codeclass="language-lisp">(defclass foo ()
((name :type number :initform "17")))
</code></pre>
<p>throws a warning at compile time.</p>
<p>Note: see also <ahref="https://github.com/fisxoj/sanity-clause">sanity-clause</a>, a data
serialization/contract library to check slots’ types during
<code>make-instance</code> (which is not compile time).</p>
<h3id="alternative-type-checking-syntax-defstar-serapeum">Alternative type checking syntax: defstar, serapeum</h3>
<p>The <ahref="https://github.com/ruricolist/serapeum/blob/master/REFERENCE.md#types">Serapeum</a> library provides a shortcut that looks like this:</p>
a <code>defun*</code> macro that allows to add the type declarations into the
lambda list. It looks like this:</p>
<pre><codeclass="language-lisp">(defun* sum ((a real) (b real))
(+ a b))
</code></pre>
<p>It also allows:</p>
<ul>
<li>to declare the return type, either in the function definition or in its body</li>
<li>to quickly declare variables that are ignored, with the <code>_</code> placeholder</li>
<li>to add assertions for each arguments</li>
<li>to do the same with <code>defmethod</code>, <code>defparameter</code>, <code>defvar</code>, <code>flet</code>, <code>labels</code>, <code>let*</code> and <code>lambda</code>.</li>
</ul>
<h3id="limitations">Limitations</h3>
<p>Complex types involving <code>satisfies</code> are not checked inside a function
body by default, only at its boundaries. Even if it does a lot, SBCL doesn’t do
as much as a statically typed language.</p>
<p>Consider this example, where we badly increment an integer with a
; (LOOP FOR NAME IN *ALL-NAMES* RETURN (INCF RES NAME)))))
;
; caught WARNING:
; Derived type of ("a hairy form" NIL (SETQ RES (+ NAME RES))) is
; (VALUES (OR NULL NUMBER) &OPTIONAL),
; conflicting with the declared function return type
; (VALUES STRING &REST T).
</code></pre>
<p>We could also use a <code>the</code> declaration in the loop body to get a compile-time warning:</p>
<pre><codeclass="language-lisp"> do (incf res (the string name)))
</code></pre>
<p>What can we conclude? This is yet another reason to decompose your
code into small functions.</p>
<h2id="see-also">See also</h2>
<ul>
<li>the article <ahref="https://medium.com/@MartinCracauer/static-type-checking-in-the-programmable-programming-language-lisp-79bb79eb068a">Static type checking in SBCL</a>, by Martin Cracauer</li>
<li>the article <ahref="https://alhassy.github.io/TypedLisp">Typed List, a Primer</a> - let’s explore Lisp’s fine-grained type hierarchy! with a shallow comparison to Haskell.</li>
<li>the <ahref="https://github.com/coalton-lang/coalton/">Coalton</a> library: an
efficient, statically typed functional programming language that
supercharges Common Lisp. It is as an embedded DSL in Lisp that
resembles Haskell or Standard ML, but lets you seamlessly
interoperate with non-statically-typed Lisp code (and vice versa).</li>
<li><ahref="https://dev.to/vindarel/compile-time-exhaustiveness-checking-in-common-lisp-with-serapeum-5c5i">exhaustiveness type checking at compile-time</a> with <ahref="https://github.com/ruricolist/serapeum/blob/master/REFERENCE.md#ecase-of-type-x-body-body">Serapeum</a> for enum types and union types (ecase-of, etypecase-of).</li>
</ul>
<hr/>
<divclass="footnotes"role="doc-endnotes">
<ol>
<liid="fn:1"role="doc-endnote">
<p>The term <em>object</em> here has nothing to do with Object-Oriented or so. It
means “any Lisp datum”.<ahref="type.html#fnref:1"class="reversefootnote"role="doc-backlink">↩</a></p>
📹 Discover <astyle="color: darkgrey; text-decoration: underline",href="https://www.udemy.com/course/common-lisp-programming/?referralCode=2F3D698BBC4326F94358">our contributor's Common Lisp video course on Udemy</a>