Key takeaways 100 Lisp interview questions, grouped by level: freshers, intermediate, experienced and coding. Every answer starts with a one-line “Quick answer” you can say out loud, followed by the explanation and runnable code. Use the filter bar to practise only the level you are interviewing for, then test yourself with the free Lisp quiz. What is Lisp, and why do interviewers ask about it? This page provides a complete collection of Lisp Interview Questions and Answers designed for software developers, programmers, AI engineers, functional programming enthusiasts, and candidates preparing for technical interviews.
Lisp is one of the oldest and most influential programming languages. It introduced concepts such as symbolic computation, functional programming, recursion, garbage collection, and dynamic typing. Lisp is widely known for its importance in artificial intelligence, language research, and advanced software development.
This interview guide covers beginner, intermediate, and advanced Lisp concepts including Lisp syntax, lists, atoms, S-expressions, recursion, functional programming, macros, lambda expressions, evaluation models, Common Lisp, Scheme, and real-world programming scenarios.
Why companies hire for Lisp Pioneered functional programming and recursion – a foundational language in computer science Powerful macro system – allows metaprogramming and code-as-data (homoiconicity) Symbolic computation – ideal for AI, natural language processing, and research Dynamic and interactive development – REPL-driven programming for rapid prototyping Multiple dialects – Common Lisp, Scheme, Clojure provide flexibility for different domains Influenced many modern languages – concepts adopted in Python, Ruby, JavaScript, and more Strong community and rich ecosystem for academic and industry applications All 100 Freshers 11 Intermediate 9 Experienced 20 Coding 60 100 shown
Basic Lisp Interview Questions for Freshers 11 questions Start here if you are a fresher or switching to Lisp. These fundamentals are asked in almost every first-round and campus interview.
1 How interviewers ask it “Let's start with the basics — how would you explain Lisp?”
Beginner Lisp
Quick answer Lisp is a family of programming languages with a long history, designed for symbolic computation and artificial intelligence. It is known for its unique syntax, powerful macro system, and support for functional programming.
Symbolic computation : Designed for manipulating symbolsFunctional programming : First-class functionsMacros : Powerful meta-programming capabilitiesGarbage collection : Automatic memory managementREPL : Interactive development environment LispCopy
(format t "Hello, World!" )2 How interviewers ask it “How would you declare variables? Walk me through your approach.”
Beginner Lisp
Quick answer Variables in Lisp are declared using defvar (global), defparameter (global mutable), and let (local).
defvar : Global variable (mutable)defparameter : Global variable (mutable)let : Local variableDynamic typing : Variables can hold any typesetf : Used to assign values LispCopy
(defparameter *mutable-var* "Hello" )
(defvar *immutable-var* "World" )
(let ((local-var "Local" ))
(format t local-var))
(setf *mutable-var* "Updated" )
(format t *mutable-var* )3 How interviewers ask it “In simple words, what are the data types? Explain it like you would to a new teammate.”
Beginner Lisp
Quick answer Lisp has a rich set of data types including numbers, characters, strings, symbols, lists, arrays, and hash tables.
Numbers : Integers, floats, ratiosBooleans : t and nilCharacters : #\AStrings : "Hello Lisp"Symbols : hello-symbolLists : (1 2 3 4 5)Arrays : make-array LispCopy
(defparameter *int-num* 10 )
(defparameter *float-num* 3.14 )
(defparameter *ratio-num* 1/2 )
(defparameter *is-active* t )
(defparameter *is-inactive* nil )
(defparameter *char* #\A)
(defparameter *str* "Hello Lisp" )
(defparameter *sym* 'hello-symbol)
(defparameter *list* '(1 2 3 4 5 ))
(defparameter *array* (make-array 5 :initial-contents '(1 2 3 4 5 )))
(typep 10 'integer) 4 How interviewers ask it “Suppose you need to define functions in Lisp — how do you approach it, and what can go wrong?”
Beginner Lisp
Quick answer Functions in Lisp are defined using the defun macro. They support optional parameters, multiple return values, and higher-order functions.
Basic : (defun name (params) body)Documentation : Strings after paramsOptional params : &optionalMultiple return values : (values)Higher-order : Functions as arguments LispCopy
(defun add (a b)
(+ a b))
(defun subtract (a b)
"Subtract b from a"
(- a b))
(defun greet (&optional (name "Guest" ))
(format nil "Hello, ~a!" name))
(defun divide (a b)
(values (/ a b) (mod a b)))
(defun operate (a b operation)
(funcall operation a b))
(defparameter *multiply* (lambda (a b) (* a b)))
(format t "~a" (add 5 3 ))
(format t "~a" (subtract 10 4 ))
(format t "~a" (greet "Alice" ))
(format t "~a" (operate 6 7 *multiply* ))5 How interviewers ask it “In simple words, what are arrays? Explain it like you would to a new teammate.”
Beginner Lisp
Quick answer Arrays in Lisp are created with make-array and accessed with aref. Vectors are one-dimensional arrays.
Creation : (make-array size)Access : (aref arr index)Modify : (setf (aref arr index) value)Vectors : #(1 2 3)Operations : array-dimension LispCopy
(defparameter *numbers* (make-array 5 :initial-contents '(1 2 3 4 5 )))
(defparameter *strings* (make-array 3 :initial-contents '("Apple" "Banana" "Orange" )))
(aref *numbers* 2 )
(setf (aref *numbers* 2 ) 10 )
(array-dimension *numbers* 0 )
(array-dimensions *numbers* )
(dotimes (i (length *numbers* ))
(format t "~a " (aref *numbers* i)))
(defparameter *vector* #(1 2 3 4 5 ))
(map 'vector (lambda (x ) (* x 2 )) *numbers* )
(defparameter *list* '(1 2 3 ))
(defparameter *array-2* (make-array 3 :initial-contents '(1 2 3 ))) 6 How interviewers ask it “Let's start with the basics — how would you explain collections in Lisp?”
Beginner Lisp
Quick answer Lisp collections include lists, sets, and hash tables. Lists are the most common and versatile collection type.
Lists : (list 1 2 3)Sets : (remove-duplicates)Maps : make-hash-tableOperations : filter, map, reduceModification : push, pop LispCopy
(defparameter *immutable-list* '(1 2 3 4 5 ))
(defparameter *mutable-list* (list 1 2 3 ))
(setf (cdr (cdr *mutable-list* )) (list 4 ))
(defparameter *set* (remove-duplicates '(1 2 3 3 )))
(defparameter *immutable-map* '((key1 . value1) (key2 . value2)))
(defparameter *mutable-map* (make-hash-table ))
(setf (gethash 'key1 *mutable-map* ) "value1" )
(setf (gethash 'key2 *mutable-map* ) "value2" )
(defparameter *numbers* '(1 2 3 4 5 6 ))
(defparameter *evens* (remove-if-not #'evenp *numbers* ))
(defparameter *doubled* (mapcar (lambda (x ) (* x 2 )) *numbers* ))
(defparameter *sum* (reduce #'+ *numbers* ))
(defparameter *exists* (some (lambda (x ) (> x 10 )) *numbers* ))
(defparameter *all-even* (every #'evenp *numbers* ))
(format t "~a" *evens* )
(format t "~a" *doubled* )
(format t "~a" *sum* )7 How interviewers ask it “Let's start with the basics — how would you explain structs (data classes) in Lisp?”
Beginner Lisp
Quick answer Structs in Lisp are defined with defstruct and provide accessor functions, constructors, and copying.
Definition : (defstruct person name age city)Constructor : (make-person :name "Alice")Accessors : (person-name obj)Copy : (copy-person obj)Default values : (city "Unknown") LispCopy
(defstruct person
name
age
(city "Unknown" ))
(defparameter *person1* (make-person :name "Alice" :age 25 :city "NYC" ))
(defparameter *person2* (copy-person *person1* ))
(setf (person-age *person2* ) 26 )
(person-name *person1* )
(person-age *person1* )
(person-city *person1* )
(format t "~a" *person1* )8 How interviewers ask it “In simple words, what are sealed classes? Explain it like you would to a new teammate.”
Beginner Lisp
Quick answer Lisp uses CLOS (Common Lisp Object System) for object-oriented programming. Sealed classes can be simulated using generic functions and classes.
Generic functions : defgenericClasses : defclassMethods : defmethodPolymorphism : Based on class typesMulti-methods : Multiple dispatch LispCopy
(defgeneric handle-result (result ))
(defclass success ()
((data :initarg :data :accessor data)))
(defclass error ()
((message :initarg :message :accessor message)))
(defclass loading ()
())
(defmethod handle-result ((result success))
(format t "Success: ~a" (data result)))
(defmethod handle-result ((result error))
(format t "Error: ~a" (message result)))
(defmethod handle-result ((result loading))
(format t "Loading..." ))
(defgeneric area (shape ))
(defclass circle ()
((radius :initarg :radius :accessor radius)))
(defclass rectangle ()
((width :initarg :width :accessor width)
(height :initarg :height :accessor height)))
(defclass point ()
())
(defmethod area ((shape circle))
(* pi (expt (radius shape) 2 )))
(defmethod area ((shape rectangle))
(* (width shape) (height shape)))
(defmethod area ((shape point))
0 )
(handle-result (make-instance 'success :data "Data loaded" ))
(format t "~a" (area (make-instance 'circle :radius 5.0 )))9 How interviewers ask it “Let's start with the basics — how would you explain null safety in Lisp?”
Beginner Lisp
Quick answer Lisp uses nil to represent null values. Null safety is achieved through conditional checks and functions that handle nil gracefully.
nil : Represents null/falseConditionals : when, ifSafe functions : when, unlessElvis operator : Custom implementationType checking : typep LispCopy
(defparameter *unset* :unset )
(defun safe-length (list )
(if list (length list) 0 ))
(defun safe-call (obj &optional default)
(if obj (funcall obj) default))
(defun elvis (value default)
(if value value default))
(defun safe-type (obj type)
(if (typep obj type) obj nil ))
(defun process-string (str )
(when str
(format t "String is: ~a" str)
(format t "Length: ~a" (length str))))
(process-string "Hello" )
(process-string nil )
(elvis nil "default" )
(safe-type 10 'integer)10 How interviewers ask it “Let's start with the basics — how would you explain control flow statements in Lisp?”
Beginner Lisp
Quick answer Lisp provides control flow through if, cond, loop, dotimes, and do.
If-else : (if condition then else)Cond : (cond ((condition) result) ...)Loop : (loop for i from 1 to 10)Dotimes : (dotimes (i 5) body)Do : (do ((i 0 (1+ i))) ((>= i 5))) LispCopy
(defparameter *age* 25 )
(defparameter *status* (if (< *age* 18 ) "Minor" "Adult" ))
(format t *status* )
(defparameter *grade* 'A)
(defparameter *result* (cond
((eq *grade* 'A) "Excellent" )
((eq *grade* 'B) "Good" )
((eq *grade* 'C) "Fair" )
(t "Needs Improvement" )))
(format t *result* )
(defparameter *score* 85 )
(defparameter *grade2* (cond
((<= 90 *score* 100 ) "A" )
((<= 80 *score* 89 ) "B" )
((<= 70 *score* 79 ) "C" )
(t "F" )))
(dotimes (i 5 )
(format t "~a " i))
(loop for i from 1 to 10 by 2
do (format t "~a " i))
(loop for i from 10 downto 1
do (format t "~a " i))
(defparameter *i* 0 )
(loop while (< *i* 5 )
do (format t "~a " *i* )
(incf *i* ))
(loop do (format t "~a " *i* )
(decf *i* )
while (> *i* 0 ))11 How interviewers ask it “Let's start with the basics — how would you explain classes and inheritance in Lisp?”
Beginner Lisp
Quick answer CLOS provides a powerful object system with classes, inheritance, and multiple dispatch. Classes are defined with defclass.
Class : (defclass person () ((name)))Inheritance : (defclass dog (animal) ((breed)))Generic functions : defgenericMethods : defmethodInterfaces : Simulated via generic functions LispCopy
(defclass animal ()
((name :initarg :name :accessor name)))
(defgeneric make-sound (animal ))
(defclass dog (animal )
((breed :initarg :breed :accessor breed)))
(defmethod make-sound ((animal animal))
(format t "Animal sound" ))
(defmethod make-sound ((dog dog))
(format t "Woof!" ))
(defclass vehicle ()
((started :initform nil :accessor started)))
(defgeneric start (vehicle ))
(defmethod start ((vehicle vehicle))
(setf (started vehicle) t )
(format t "Started" ))
(defgeneric fly (obj ))
(defgeneric land (obj ))
(defgeneric swim (obj ))
(defclass duck ()
())
(defmethod fly ((duck duck))
(format t "Flying" ))
(defmethod land ((duck duck))
(format t "Landing..." ))
(defmethod swim ((duck duck))
(format t "Swimming" ))
(defparameter *dog* (make-instance 'dog :name "Rex" :breed "German Shepherd" ))
(make-sound *dog* )
(name *dog* )
(defparameter *duck* (make-instance 'duck))
(fly *duck* )
(swim *duck* )
Advanced Lisp Interview Questions for Experienced Developers 20 questions Senior-level Lisp questions on internals, performance, design and trade-offs — typical for 3, 5 and 7+ years of experience.
21 How interviewers ask it “How would you explain coroutines to a junior engineer, and what do people most often get wrong?”
Advanced Lisp
Quick answer Lisp doesn't have built-in coroutines, but they can be simulated using threads, closures, or custom implementations.
Threads : sb-thread:make-threadClosures : Stateful functionsSuspending : Custom continuation passingStructured concurrency : Thread managementDispatchers : Thread pools LispCopy
(defun fetch-data ()
(sleep 1 )
"Data loaded" )
(defun main-launch ()
(let ((thread (sb-thread :make-thread
(lambda ()
(sleep 2 )
(format t "Thread completed" )))))
(sb-thread :join-thread thread)))
(defun async-fetch ()
(sb-thread :make-thread #'fetch-data))
(defun await-result (thread )
(sb-thread :join-thread thread))
(defun parallel-tasks ()
(let* ((task1 (async-fetch ))
(task2 (async-fetch ))
(results (list (await-result task1) (await-result task2))))
(format t "Results: ~a" results)))
(defun with-timeout (seconds fn)
(let ((thread (sb-thread :make-thread fn)))
(sleep seconds)
(if (sb-thread :thread-alive-p thread)
(progn
(sb-thread :terminate-thread thread)
(format t "Timed out!" ))
(sb-thread :join-thread thread))))
(main-launch )
(async-fetch )
(parallel-tasks )22 How interviewers ask it “Explain flows in Lisp in detail — what should a new team member understand about them?”
Advanced Lisp
Quick answer Lisp uses streams and custom functions to simulate flows. Streams can be filtered, mapped, and collected.
Streams : Stateful functionsOperators : map, filterStateFlow : State managementSharedFlow : Shared streamsCollect : Collection of stream values LispCopy
(defun make-number-stream (n )
(let ((i 1 ))
(lambda ()
(if (<= i n)
(prog1 i (incf i))
nil ))))
(defun stream-filter (stream pred)
(lambda ()
(loop
(let ((val (funcall stream)))
(if (null val)
(return nil )
(if (funcall pred val)
(return val)))))))
(defun stream-map (stream fn)
(lambda ()
(let ((val (funcall stream)))
(if (null val)
nil
(funcall fn val)))))
(defun stream-collect (stream )
(loop for val = (funcall stream)
while val
collect val))
(defparameter *numbers* (make-number-stream 5 ))
(defparameter *filtered* (stream-filter *numbers* (lambda (x ) (evenp x))))
(defparameter *mapped* (stream-map *filtered* (lambda (x ) (format nil "Number: ~a" x))))
(format t "~a" (stream-collect *mapped* ))
(defparameter *state* 0 )
(defun get-state () *state* )
(defun set-state (val ) (setf *state* val))
(defun increment () (incf *state* ))23 How interviewers ask it “Explain channels in Lisp in detail — what should a new team member understand about them?”
Advanced Lisp
Quick answer Channels can be implemented using queues and threads for communication between different threads.
Queue : defclass queueSend/Receive : queue-enqueue, queue-dequeueBuffered : Queue capacityProducer/Consumer : Patterns for communicationClose : Notify when done LispCopy
(defclass queue ()
((items :initform '() :accessor items)
(lock :initform (sb-thread :make-mutex ) :accessor lock)))
(defun queue-enqueue (queue item)
(sb-thread :with-mutex ((lock queue))
(setf (items queue) (append (items queue) (list item)))))
(defun queue-dequeue (queue )
(sb-thread :with-mutex ((lock queue))
(let ((item (car (items queue))))
(setf (items queue) (cdr (items queue)))
item)))
(defun queue-size (queue )
(length (items queue)))
(defun basic-channel ()
(let ((queue (make-instance 'queue)))
(sb-thread :make-thread
(lambda ()
(queue-enqueue queue "Hello" )
(queue-enqueue queue "World" )))
(loop for i from 1 to 2
do (format t "~a" (queue-dequeue queue)))))
(defun buffered-channel ()
(let ((queue (make-instance 'queue)))
(sb-thread :make-thread
(lambda ()
(dotimes (i 5 )
(queue-enqueue queue i)
(format t "Sent: ~a" i))))
(dotimes (i 5 )
(sleep 0.1 )
(format t "Received: ~a" (queue-dequeue queue)))))24 How interviewers ask it “How would you explain sealed classes and enum classes to a junior engineer, and what do people most often get wrong?”
Advanced Lisp
Quick answer Lisp uses CLOS classes and generic functions to implement similar patterns. Enums are typically represented as symbols or keyword arguments.
Enum : defparameter *colors* '(:red :green :blue)Sealed : Classes with specific methodsProperties : Slots with valuesSubclasses : Inheritance hierarchyPolymorphism : Generic functions LispCopy
(defparameter *colors* '(:red :green :blue ))
(defparameter *status-codes* '((:success . 200 )
(:error . 500 )
(:loading . 100 )))
(defclass ui-state ()
())
(defclass success (ui-state )
((data :initarg :data :accessor data)))
(defclass error (ui-state )
((message :initarg :message :accessor message)))
(defclass loading (ui-state )
())
(defclass idle (ui-state )
())
(defgeneric handle-state (state ))
(defmethod handle-state ((state success))
(format t "Data: ~a" (data state)))
(defmethod handle-state ((state error))
(format t "Error: ~a" (message state)))
(defmethod handle-state ((state loading))
(format t "Loading..." ))
(defmethod handle-state ((state idle))
(format t "Idle" ))
(defclass payment () ())
(defclass cash (payment )
((amount :initarg :amount :accessor amount)))
(defclass credit-card (payment )
((number :initarg :number :accessor number)
(expiry :initarg :expiry :accessor expiry)))
(defclass paypal (payment )
((email :initarg :email :accessor email)))
(defgeneric handle-payment (payment ))
(defmethod handle-payment ((payment cash))
(format t "Cash amount: ~a" (amount payment)))
(defmethod handle-payment ((payment credit-card))
(format t "Card: ~a" (number payment)))
(defmethod handle-payment ((payment paypal))
(format t "PayPal: ~a" (email payment)))25 How interviewers ask it “Explain generics in Lisp in detail — what should a new team member understand about them?”
Advanced Lisp
Quick answer Lisp is dynamically typed, so generics aren't needed. However, type checking and constraints can be implemented with typep.
Dynamic typing : Values can be any typeType checking : typepConstraints : Validation in functionsVariance : Not applicablePolymorphism : Generic functions LispCopy
(defclass box ()
((value :initarg :value :accessor value)))
(defun swap (first second)
(values second first))
(defun sum-numbers (items )
(apply #'+ items))
(defclass producer ()
((produce :initarg :produce :accessor produce)))
(defclass consumer ()
((consume :initarg :consume :accessor consume)))
(defclass transformer ()
((transform :initarg :transform :accessor transform)))
(defun process-sequence (seq )
(mapcar (lambda (x ) (format nil "~a" x)) seq))
(defparameter *box* (make-instance 'box :value "Hello" ))
(value *box* )
(multiple-value-bind (a b) (swap 1 2 )
(format t "~a, ~a" a b))
(sum-numbers '(1 2 3 4 5 ))26 How interviewers ask it “Walk me through delegation in Lisp. Where does it come up in real systems?”
Advanced Lisp
Quick answer Delegation in Lisp is implemented using composition and forwarding methods. Classes can delegate to other objects.
Composition : Using instance variablesForwarding : Methods that call delegatesLazy initialization : Compute on demandObservable : Custom delegation patternsVetoable : Validation before delegation LispCopy
(defclass repository ()
())
(defgeneric get-data (repo ))
(defgeneric save-data (repo data))
(defclass database-repository (repository )
())
(defmethod get-data ((repo database-repository))
"Data from database" )
(defmethod save-data ((repo database-repository) data)
(format t "Saving to database: ~a" data))
(defclass cached-repository (repository )
((delegate :initarg :delegate :accessor delegate)
(cache :initform nil :accessor cache)))
(defmethod get-data ((repo cached-repository))
(or (cache repo)
(let ((data (get-data (delegate repo))))
(setf (cache repo) data)
data)))
(defclass lazy-property ()
((expensive-value :initform nil :accessor expensive-value)))
(defun get-expensive-value (obj )
(unless (slot-value obj 'expensive-value)
(format t "Computing..." )
(setf (slot-value obj 'expensive-value) "Result" ))
(slot-value obj 'expensive-value))
(defclass observable-property ()
((name :initform "Initial" :accessor name)))
(defgeneric set-name (obj value))
(defmethod set-name ((obj observable-property) value)
(let ((old (name obj)))
(setf (slot-value obj 'name) value)
(format t "~a -> ~a" old value)))
(defparameter *db* (make-instance 'database-repository))
(defparameter *cached* (make-instance 'cached-repository :delegate *db* ))
(get-data *cached* )
(get-data *cached* )
(defparameter *lazy* (make-instance 'lazy-property))
(get-expensive-value *lazy* )
(get-expensive-value *lazy* )27 How interviewers ask it “Explain object declarations and singletons in Lisp in detail — what should a new team member understand about them?”
Advanced Lisp
Quick answer Lisp implements singletons using closures or packages. A closure can encapsulate private state and provide controlled access.
Closure : Function with private statePackage : Namespace with global stateThread-safe : Locking mechanismsGlobal access : Through exported symbolsInitialization : Automatic on load LispCopy
(defun make-app-config ()
(let ((api-url "https://api.example.com" )
(timeout 5000 ))
(lambda (command &optional value)
(cond
((eq command 'get-api-url) api-url)
((eq command 'get-timeout) timeout)
((eq command 'print-config)
(format t "API URL: ~a~%Timeout: ~a" api-url timeout))
(t nil )))))
(defparameter *app-config* (make-app-config ))
(defpackage :app-config
(:use :cl )
(:export :api-url :timeout :print-config ))
(in-package :app-config )
(defparameter *api-url* "https://api.example.com" )
(defparameter *timeout* 5000 )
(defun print-config ()
(format t "API URL: ~a~%Timeout: ~a" *api-url* *timeout* ))
(in-package :cl )
(funcall *app-config* 'get-api-url)
(funcall *app-config* 'print-config)
app-config::*api-url*28 How interviewers ask it “How would you create DSL? Walk me through your approach.”
Advanced Lisp
Quick answer Lisp macros are perfect for creating DSLs. They allow custom syntax and compile-time code generation.
Macros : defmacroBuilder pattern : Configure with macrosLambdas : For custom syntaxScope functions : with-* macrosType-safe builders : HTML, XML, etc. LispCopy
(defmacro html (&body body)
`(with-output-to-string (*standard-output*)
,@body))
(defmacro body (&body body)
`(progn
(format t "<body>" )
,@body
(format t "</body>" )))
(defmacro h1 (text )
`(format t "<h1>~a</h1>" ,text))
(defmacro p (text )
`(format t "<p>~a</p>" ,text))
(defclass user-builder ()
((name :initform "" :accessor name)
(age :initform 0 :accessor age)
(email :initform "" :accessor email)))
(defun build-user (builder )
(list :name (name builder)
:age (age builder)
:email (email builder)))
(defun user (&rest args)
(let ((builder (make-instance 'user-builder)))
(dolist (arg args)
(cond
((eq (car arg) :name ) (setf (name builder) (cdr arg)))
((eq (car arg) :age ) (setf (age builder) (cdr arg)))
((eq (car arg) :email ) (setf (email builder) (cdr arg)))))
(build-user builder)))
(html
(body
(h1 "Welcome to Lisp DSL" )
(p "This is a paragraph" )
(p "Another paragraph" )))
(user :name "Alice" :age 25 :email "alice@example.com" )29 How interviewers ask it “Explain annotations in Lisp in detail — what should a new team member understand about them?”
Advanced Lisp
Quick answer Lisp uses metadata and macros for annotations. Functions can have metadata attached using get and setf.
Metadata : (setf (get symbol 'annotations) value)Macros : defmacro for custom annotationsReflection : Inspecting metadataRepeatable : Multiple annotationsUsage : get to retrieve LispCopy
(defmacro defannotated (name &rest body)
`(progn
(defparameter ,name
(list :annotations ',(car body) :value ,(cadr body)))))
(defun annotate (obj &rest annotations)
(setf (get obj 'annotations) annotations))
(defun get-annotations (obj )
(get obj 'annotations))
(defun annotated-method ()
(format t "Annotated method" ))
(annotate 'annotated-method :value "test" )
(defun read-annotations (symbol )
(get symbol 'annotations))
(defun add-annotation (symbol annotation)
(push annotation (get symbol 'annotations)))
(add-annotation 'annotated-method :permission "read" )
(add-annotation 'annotated-method :permission "write" )
(annotated-method )
(read-annotations 'annotated-method)30 How interviewers ask it “Suppose you need to use reflection in Lisp — how do you approach it, and what can go wrong?”
Advanced Lisp
Quick answer Lisp provides reflection through CLOS and the Meta-Object Protocol (MOP). Classes, slots, and methods can be inspected at runtime.
Class : class-name, class-ofSlots : class-slotsMethods : generic-function-methodsCall : funcall for dynamic callsConstructors : make-instance LispCopy
(defclass person ()
((name :initarg :name :accessor name)
(age :initarg :age :accessor age)
(city :initarg :city :accessor city
:initform "Unknown" )))
(defmethod greet ((obj person))
(format nil "Hello, my name is ~a" (name obj)))
(defmethod update-age ((obj person) new-age)
(setf (age obj) new-age))
(defun basic-reflection ()
(let ((person (make-instance 'person :name "Alice" :age 25 )))
(format t "Class: ~a" (class-name (class-of person)))
(format t "Slots: ~a" (closer-mop :class-slots (class-of person)))))
(defun access-slots ()
(let ((person (make-instance 'person :name "Alice" :age 25 )))
(dolist (slot (closer-mop :class-slots (class-of person)))
(let ((name (closer-mop :slot-definition-name slot)))
(format t "~a = ~a" name (slot-value person name))))))
(defun call-functions ()
(let ((person (make-instance 'person :name "Alice" :age 25 )))
(format t "~a" (greet person))
(update-age person 30 )
(format t "Updated age: ~a" (age person))))
(defun create-instance ()
(make-instance 'person :name "Bob" :age 30 :city "NYC" ))31 How interviewers ask it “Walk me through coroutine contexts and dispatchers in Lisp. Where do they come up in real systems?”
Advanced Lisp
Quick answer Threads in Lisp can be used with different priorities and thread-local storage for context management.
Threads : sb-thread:make-threadContext : *thread-local*Dispatcher : Thread poolsCustom context : Named threadsThread-local : make-hash-table LispCopy
(defun dispatcher-example ()
(let ((threads '()))
(push (sb-thread :make-thread
(lambda () (format t "Default: ~a" (sb-thread :thread-name sb-thread:*current-thread* ))))
threads)
(push (sb-thread :make-thread
(lambda () (format t "IO: ~a" (sb-thread :thread-name sb-thread:*current-thread* ))))
threads)
(format t "Main: ~a" (sb-thread :thread-name sb-thread:*current-thread* ))
(dolist (thread threads)
(sb-thread :join-thread thread))))
(defun custom-context ()
(sb-thread :make-thread
(lambda ()
(format t "Context: Custom" ))))
(defparameter *thread-local* (make-hash-table ))
(defun get-thread-local ()
(gethash (sb-thread :thread-name sb-thread:*current-thread* ) *thread-local* ))
(defun set-thread-local (value )
(setf (gethash (sb-thread :thread-name sb-thread:*current-thread* ) *thread-local* ) value))
(defun thread-local-example ()
(set-thread-local "Main" )
(let ((thread (sb-thread :make-thread
(lambda ()
(set-thread-local "IO" )
(format t "ThreadLocal: ~a" (get-thread-local ))))))
(sb-thread :join-thread thread))
(format t "ThreadLocal restored: ~a" (get-thread-local )))32 How interviewers ask it “How would you handle shared mutable state in coroutines? Walk me through your approach.”
Advanced Lisp
Quick answer Lisp uses locks and mutexes for synchronization. sb-thread:with-mutex ensures thread-safe operations.
Mutex : sb-thread:make-mutexAtomic : sb-thread:with-mutexSingle-threaded : Using thread poolsActor : State encapsulationChannels : Communication between threads LispCopy
(defclass counter-with-mutex ()
((value :initform 0 :accessor value)
(lock :initform (sb-thread :make-mutex ) :accessor lock)))
(defun increment-counter (counter )
(sb-thread :with-mutex ((lock counter))
(incf (value counter))))
(defun get-counter-value (counter )
(value counter))
(defclass counter-with-atomic ()
((value :initform 0 :accessor value)))
(defun increment-atomic (counter )
(sb-thread :with-mutex ((lock counter))
(incf (value counter))))
(defclass counter-with-single-thread ()
((value :initform 0 :accessor value)
(lock :initform (sb-thread :make-mutex ) :accessor lock)))
(defun increment-single (counter )
(sb-thread :with-mutex ((lock counter))
(incf (value counter))))
(defun counter-example ()
(let ((counter (make-instance 'counter-with-mutex)))
(loop for i from 1 to 1000
do (sb-thread :make-thread
(lambda ()
(dotimes (j 100 )
(increment-counter counter)))))
(sleep 5 )
(format t "Final count: ~a" (get-counter-value counter))))33 How interviewers ask it “Walk me through flow operators and transformations in Lisp. Where do they come up in real systems?”
Advanced Lisp
Quick answer Lisp streams can be transformed using functions like mapcar, remove-if-not, and custom stream operators.
filter : remove-if-notmap : mapcarbuffer : Custom bufferingconflate : Drop intermediate valuescollect latest : Latest value processing LispCopy
(defun make-number-stream (n )
(let ((i 0 ))
(lambda ()
(if (< i n)
(prog1 i (incf i))
nil ))))
(defun flow-transform-example ()
(let ((stream (make-number-stream 10 )))
(loop for val = (funcall stream)
while val
when (evenp val)
do (format t "Number ~a" val))))
(defun flow-buffer-example ()
(let ((stream (make-number-stream 5 )))
(loop for val = (funcall stream)
while val
do (format t "~a" val))))
(defun flow-conflate-example ()
(let ((stream (make-number-stream 10 )))
(loop for val = (funcall stream)
while val
do (progn
(sleep 0.1 )
(format t "~a" val)))))
(defun flow-collect-latest-example ()
(let ((stream (make-number-stream 10 )))
(loop for val = (funcall stream)
while val
do (progn
(format t "Processing ~a" val)
(sleep 0.1 )
(format t "Done ~a" val)))))
(defun flow-flatmap-example ()
(let ((stream (make-number-stream 3 )))
(loop for val = (funcall stream)
while val
do (loop for letter in '(a b)
do (format t "~a-~a" val letter)))))34 How interviewers ask it “Explain coroutine scopes and lifecycle in Lisp in detail — what should a new team member understand about them?”
Advanced Lisp
Quick answer Thread management in Lisp provides lifecycle control. Threads can be created, joined, and terminated.
Scope : Custom thread managersLifecycle : sb-thread:make-threadGlobalScope : Application-wide threadsSupervisorJob : Independent job hierarchyCancellation : Thread termination LispCopy
(defclass my-scope ()
((threads :initform '() :accessor threads)
(cancelled :initform nil :accessor cancelled)))
(defun scope-launch (scope fn)
(push (sb-thread :make-thread fn) (threads scope)))
(defun scope-cancel (scope )
(setf (cancelled scope) t )
(dolist (thread (threads scope))
(sb-thread :terminate-thread thread)))
(defclass lifecycle-scope (my-scope )
())
(defun launch-when-created (scope fn)
(scope-launch scope fn))
(defun on-destroy (scope )
(scope-cancel scope))
(defun scope-comparison ()
(sb-thread :make-thread
(lambda ()
(sleep 1 )
(format t "GlobalScope" )))
(let ((scope (make-instance 'my-scope)))
(scope-launch scope
(lambda ()
(sleep 1 )
(format t "CoroutineScope" )))
(sleep 2 )
(scope-cancel scope)))
(defun timeout-scope (seconds fn)
(let ((thread (sb-thread :make-thread fn)))
(sleep seconds)
(if (sb-thread :thread-alive-p thread)
(progn
(sb-thread :terminate-thread thread)
(format t "Timed out" )
nil )
(sb-thread :join-thread thread))))35 How interviewers ask it “How would you explain SharedFlow and StateFlow to a junior engineer, and what do people most often get wrong?”
Advanced Lisp
Quick answer Lisp can implement state and shared flows using observers and state management patterns with closures or classes.
StateFlow : defclass state-flowSharedFlow : defclass shared-flowReplay : Store last N valuesUpdate : state-flow-updateCombine : combine-flows LispCopy
(defclass state-flow ()
((value :initform nil :accessor value)
(observers :initform '() :accessor observers)))
(defun state-flow-update (flow new-value)
(setf (value flow) new-value)
(dolist (observer (observers flow))
(funcall observer new-value)))
(defun state-flow-observe (flow callback)
(push callback (observers flow)))
(defclass shared-flow ()
((events :initform '() :accessor events)
(replay :initarg :replay :accessor replay)
(replayed :initform '() :accessor replayed)
(observers :initform '() :accessor observers)))
(defun shared-flow-emit (flow event)
(push event (events flow))
(setf (replayed flow) (cons event (replayed flow)))
(when (> (length (replayed flow)) (replay flow))
(setf (replayed flow) (subseq (replayed flow) 0 (replay flow))))
(dolist (observer (observers flow))
(funcall observer event)))
(defun distinct-example (flow )
(let ((last-value nil ))
(state-flow-observe flow
(lambda (value )
(unless (equal value last-value)
(setf last-value value)
(format t "~a" value))))))
(defun combine-flows (flow1 flow2)
(let ((result (make-instance 'state-flow)))
(state-flow-observe flow1
(lambda (value )
(state-flow-update result
(+ value (value flow2)))))
(state-flow-observe flow2
(lambda (value )
(state-flow-update result
(+ (value flow1) value))))))36 How interviewers ask it “How would you handle exceptions in coroutines? Walk me through your approach.”
Advanced Lisp
Quick answer Lisp uses handler-case and handler-bind for exception handling in threads.
Try-catch : handler-caseExceptionHandler : Custom handlersSupervisorJob : Isolate failuresFlow catch : handler-caseSupervisorScope : handler-case LispCopy
(defun try-catch-example ()
(handler-case
(sb-thread :make-thread
(lambda ()
(error "Error" )))
(error (e )
(format t "Caught: ~a" e))))
(defun exception-handler ()
(handler-case
(sb-thread :make-thread
(lambda ()
(error "Test" )))
(error (e )
(format t "Handler caught: ~a" e))))
(defun supervisor-example ()
(let ((threads '()))
(push (sb-thread :make-thread
(lambda ()
(handler-case
(progn
(sleep 0.1 )
(error "Child 1 error" ))
(error (e )
(format t "Child 1 caught: ~a" e)))))
threads)
(push (sb-thread :make-thread
(lambda ()
(sleep 0.2 )
(format t "Child 2 still running" )))
threads)
(dolist (thread threads)
(sb-thread :join-thread thread))))
(defun flow-exception ()
(handler-case
(progn
(format t "~a" 1 )
(error "Flow error" ))
(error (e )
(format t "Flow caught: ~a" e)
(format t "-1" ))))
(defun supervisor-scope-example ()
(let ((threads '()))
(push (sb-thread :make-thread
(lambda ()
(error "Error" )))
threads)
(push (sb-thread :make-thread
(lambda ()
(sleep 0.1 )
(format t "Still running" )))
threads)
(dolist (thread threads)
(sb-thread :join-thread thread))))37 How interviewers ask it “Walk me through channel producers and consumer patterns in Lisp. Where do they come up in real systems?”
Advanced Lisp
Quick answer Lisp can implement producer-consumer patterns using queues and threads.
Producer-consumer : Single producer, single consumerFan-out : Multiple consumersFan-in : Multiple producersPipelines : Chained operationsBuffer : Queue capacity LispCopy
(defun producer-consumer ()
(let ((queue (make-instance 'queue)))
(sb-thread :make-thread
(lambda ()
(dotimes (i 20 )
(queue-enqueue queue i)
(format t "Produced: ~a" i)
(sleep 0.1 ))))
(sb-thread :make-thread
(lambda ()
(dotimes (i 20 )
(let ((val (queue-dequeue queue)))
(when val
(format t "Consumed: ~a" val)
(sleep 0.15 ))))))))
(defun fan-out-example ()
(let ((queue (make-instance 'queue)))
(sb-thread :make-thread
(lambda ()
(dotimes (i 20 )
(queue-enqueue queue i))))
(dotimes (id 3 )
(sb-thread :make-thread
(lambda ()
(dotimes (i 20 )
(let ((val (queue-dequeue queue)))
(when val
(format t "Consumer ~a: ~a" id val)
(sleep 0.1 )))))))))
(defun fan-in-example ()
(let ((queue (make-instance 'queue)))
(dotimes (id 3 )
(sb-thread :make-thread
(lambda ()
(dotimes (i 5 )
(queue-enqueue queue (format nil "Producer ~a: ~a" id i))
(sleep 0.05 )))))
(sb-thread :make-thread
(lambda ()
(dotimes (i 15 )
(format t "~a" (queue-dequeue queue)))))))38 How interviewers ask it “Suppose you need to handle thread cancellation in Lisp — how do you approach it, and what can go wrong?”
Advanced Lisp
Quick answer Lisp threads support cancellation through sb-thread:terminate-thread and cooperative cancellation using flags.
Check flag : when cancelled (return)Cancel : sb-thread:terminate-threadFinally : unwind-protectNonCancellable : Custom flagTimeout : sleep and termination LispCopy
(defun cooperative-cancellation ()
(let ((cancelled nil ))
(sb-thread :make-thread
(lambda ()
(dotimes (i 100 )
(when cancelled (return ))
(format t "Working: ~a" i)
(sleep 0.05 ))))
(sleep 0.2 )
(setf cancelled t )))
(defun cancellation-finally ()
(let ((cancelled nil ))
(sb-thread :make-thread
(lambda ()
(unwind-protect
(dotimes (i 100 )
(when cancelled (return ))
(format t "Processing: ~a" i)
(sleep 0.1 ))
(format t "Cleaning up" )
(sleep 0.1 )
(format t "Cleanup done" ))))
(sleep 0.25 )
(setf cancelled t )))
(defun cancellation-timeout ()
(let ((thread (sb-thread :make-thread
(lambda ()
(dotimes (i 10 )
(sleep 0.2 )
(format t "Iteration: ~a" i))))))
(sleep 1 )
(sb-thread :terminate-thread thread)
(format t "Timed out" )))
(defun custom-cancellation ()
(let ((cancelled nil ))
(sb-thread :make-thread
(lambda ()
(let ((i 0 ))
(loop while (and (not cancelled) (< i 1000 ))
do (when (= (mod i 100 ) 0 )
(format t "Still running: ~a" i))
(incf i)
(sleep 0.001 )))))
(sleep 0.1 )
(setf cancelled t )))39 How interviewers ask it “Suppose you need to test threads in Lisp — how do you approach it, and what can go wrong?”
Advanced Lisp
Quick answer Lisp testing frameworks like fiveam or lisp-unit can test threaded code with assertions.
runTest : Custom test runneradvanceTimeBy : sleep for timingadvanceUntilIdle : Wait for threadsTestDispatcher : Custom thread managementAssertions : assert LispCopy
(defun test-coroutine ()
(let ((result nil ))
(sb-thread :make-thread
(lambda ()
(sleep 1 )
(setf result "Success" )))
(sleep 1.5 )
(assert (equal result "Success" ) () "Test failed" )))
(defun test-with-delay ()
(let ((result nil ))
(sb-thread :make-thread
(lambda ()
(sleep 1 )
(setf result "Done" )))
(sleep 1 )
(assert (equal result "Done" ) () "Test failed" )))
(defun test-multiple-coroutines ()
(let ((results '()))
(sb-thread :make-thread
(lambda ()
(sleep 0.5 )
(push "Task 1" results)))
(sb-thread :make-thread
(lambda ()
(sleep 0.3 )
(push "Task 2" results)))
(sleep 1 )
(assert (equal results '("Task 2" "Task 1" )) () "Test failed" )))
(defun test-flow ()
(let ((values '()))
(dotimes (i 2 )
(push i values))
(assert (equal values '(1 0 )) () "Test failed" )))
(defun time-control-test ()
(let ((counter 0 )
(running t ))
(sb-thread :make-thread
(lambda ()
(loop while running
do (sleep 1 )
(incf counter))))
(sleep 3 )
(setf running nil )
(assert (<= counter 4 ) () "Test failed" )))40 How interviewers ask it “Walk me through Lisp Multiplatform. Where does it come up in real systems?”
Advanced Lisp
Quick answer Lisp implementations can be ported across platforms. Feature flags ( #+sbcl, #+clisp) handle platform-specific code.
Lisp implementations can be ported across platforms. Feature flags (#+sbcl, #+clisp) handle platform-specific code.
Feature flags : #+sbcl, #+clispPlatform-specific : Different implementationsSerialization : formatCross-platform : Portable codeImplementation : SBCL, CLISP, CCL, ABCL LispCopy
(defun platform-name ()
#+sbcl "SBCL"
#+clisp "CLISP"
#+ccl "CCL"
#+abcl "ABCL"
#-(or sbcl clisp ccl abcl) "Unknown" )
(defun greet ()
(format nil "Hello from ~a" (platform-name )))
(defclass platform ()
())
(defmethod get-version ((obj platform))
#+sbcl "2.2.0"
#+clisp "2.49"
#+ccl "1.12"
#+abcl "1.8.0"
#-(or sbcl clisp ccl abcl) "Unknown" )
(defclass platform-info ()
())
(defun get-info ()
(format nil "~a version ~a"
(greet ) (get-version (make-instance 'platform))))
(defun encode-user (user )
(format nil "~a~%~a~%~a"
(getf user :id )
(getf user :name )
(getf user :email )))
(defun decode-user (data )
(let ((lines (split-string data #Newline)))
(list :id (parse-integer (first lines))
:name (second lines)
:email (third lines))))
Lisp Coding Interview Questions (Programs with Code) 60 questions Hands-on Lisp programs that are asked in coding rounds and machine tests. Read the code, then try writing it yourself without looking.
41 How interviewers ask it “Can you reverse a string in Lisp? Then walk me through the edge cases you would test.”
Coding Lisp
Quick answer Reverse a string using reverse or manual iteration.
Built-in : (reverse str)Manual : (with-output-to-string ...)Complexity : O(n) time LispCopy
(defun reverse-string (str )
(reverse str))
(format t "~a" (reverse-string "hello" ))
(defun reverse-string-loop (str )
(with-output-to-string (s )
(do ((i (1 - (length str)) (1 - i)))
((< i 0 ))
(write-char (char str i) s))))42 How interviewers ask it “Coding-round task — check palindrome in Lisp. Explain your approach before you write the code.”
Coding Lisp
Quick answer Check if a string is a palindrome using reverse or two-pointer approach.
Method : (string= cleaned (reverse cleaned))Two-pointer : Compare from both endsCase insensitive : string-downcaseIgnore non-alphanumeric : remove-if-not #'alphanumericp LispCopy
(defun is-palindrome (str )
(let ((cleaned (string-downcase
(remove-if-not #'alphanumericp str))))
(string= cleaned (reverse cleaned))))
(format t "~a" (is-palindrome "racecar" ))
(format t "~a" (is-palindrome "hello" ))
(defun is-palindrome-two-pointer (str )
(let ((cleaned (string-downcase
(remove-if-not #'alphanumericp str)))
(left 0 )
(right (1 - (length str))))
(loop while (< left right)
do (if (char/= (char cleaned left) (char cleaned right))
(return nil )
(progn (incf left) (decf right))))))43 How interviewers ask it “Can you find max in array in Lisp? Then walk me through the edge cases you would test.”
Coding Lisp
Quick answer Find maximum value using reduce #'max or manual iteration.
Built-in : (reduce #'max arr)Manual : Iterate and track maxEmpty array : Handle with errorComplexity : O(n) time LispCopy
(defun find-max (arr )
(if (null arr)
(error "Empty array" )
(reduce #'max arr)))
(format t "~a" (find-max '(1 5 3 9 2 )))
(defun find-max-manual (arr )
(let ((max-val (car arr)))
(dolist (num (cdr arr))
(when (> num max-val)
(setf max-val num)))
max-val))44 How interviewers ask it “Coding-round task — remove duplicates in Lisp. Explain your approach before you write the code.”
Coding Lisp
Quick answer Remove duplicates using remove-duplicates or manual set implementation.
Built-in : (remove-duplicates arr)Manual : Track seen elementsComplexity : O(n²) or O(n) LispCopy
(defun remove-duplicates-list (arr )
(remove-duplicates arr))
(format t "~a" (remove-duplicates-list '(1 2 2 3 3 4 )))
(defun remove-duplicates-set (arr )
(coerce (make-hash-table ) 'list))45 How interviewers ask it “Coding-round task — merge arrays in Lisp. Explain your approach before you write the code.”
Coding Lisp
Quick answer Merge arrays using append or manual concatenation.
Built-in : (append arr1 arr2)Alternative : (concatenate 'list arr1 arr2)Unique : remove-duplicates LispCopy
(defun merge-arrays (arr1 arr2)
(append arr1 arr2))
(format t "~a" (merge-arrays '(1 2 ) '(3 4 )))
(defun merge-arrays-plus (arr1 arr2)
(append arr1 arr2))46 How interviewers ask it “Coding-round task — convert string to number in Lisp. Explain your approach before you write the code.”
Coding Lisp
Quick answer Convert using parse-integer or safe conversion.
toInt : (parse-integer str)Safe : handler-caseError handling : Return nil on failure LispCopy
(defun string-to-number (str )
(parse-integer str))
(format t "~a" (string-to-number "42" ))
(defun string-to-number-safe (str )
(handler-case
(parse-integer str)
(error () nil )))47 How interviewers ask it “Coding-round task — loop through map in Lisp. Explain your approach before you write the code.”
Coding Lisp
Quick answer Iterate through alist using dolist or mapc.
dolist : (dolist (pair alist) ...)mapc : (mapc (lambda (pair) ...) alist)Keys : mapcar #'carValues : mapcar #'cdr LispCopy
(defun loop-map (alist )
(dolist (pair alist)
(format t "~a => ~a" (car pair) (cdr pair))))
(defun loop-map-alternate (alist )
(mapc (lambda (pair )
(format t "~a => ~a" (car pair) (cdr pair)))
alist))
(loop-map '((name . "Alice" ) (age . 25 ) (city . "NYC" )))48 How interviewers ask it “Show me delay function execution in Lisp — write it out and explain each step as you go.”
Coding Lisp
Quick answer Delay using sleep or threads.
Sleep : (sleep (/ delay-ms 1000))Thread : sb-thread:make-threadAsync : sb-thread:make-thread LispCopy
(defun delayed-execution (delay-ms fn)
(sleep (/ delay-ms 1000 ))
(funcall fn))
(delayed-execution 2000
(lambda ()
(format t "After 2 seconds" )))
(defun delayed-execution-thread (delay-ms fn)
(sb-thread :make-thread
(lambda ()
(sleep (/ delay-ms 1000 ))
(funcall fn))))49 How interviewers ask it “Show me HTTP GET request in Lisp — write it out and explain each step as you go.”
Coding Lisp
Quick answer Make HTTP GET using drakma:http-request or url-request.
Drakma : (drakma:http-request url)URL-Request : (url-request:url-request url)Stream reading : read-line LispCopy
(defun fetch-data (url )
(let ((stream (drakma :http-request url)))
(when stream
(with-output-to-string (s )
(do ((line (read-line stream nil nil )
(read-line stream nil nil )))
((null line))
(write-line line s))))))
(defun fetch-data-url (url )
(let ((stream (url-request :url-request url)))
(if stream
(with-output-to-string (s )
(do ((line (read-line stream nil nil )
(read-line stream nil nil )))
((null line))
(write-line line s)))
nil )))50 How interviewers ask it “Live coding: Create a promise-like Deferred in Lisp. Talk me through your approach first.”
Coding Lisp
Quick answer Create a Deferred using threads and state management.
Thread : sb-thread:make-threadawait : sb-thread:join-threadError handling : handler-case LispCopy
(defun create-deferred (should-resolve )
(let ((thread nil )
(result nil ))
(setf thread (sb-thread :make-thread
(lambda ()
(sleep 1 )
(if should-resolve
(setf result "Success!" )
(error "Failed!" )))))
(lambda ()
(sb-thread :join-thread thread)
result)))
(defparameter *deferred* (create-deferred t ))
(handler-case
(format t "~a" (funcall *deferred* ))
(error (e )
(format t "Caught: ~a" e)))51 How interviewers ask it “Show me factorial in Lisp — write it out and explain each step as you go.”
Coding Lisp
Quick answer Calculate factorial using recursion or iteration.
Recursive : (if (<= n 1) 1 (* n (factorial (- n 1))))Iterative : do loopEdge cases : 0! = 1 LispCopy
(defun factorial (n )
(if (<= n 1 )
1
(* n (factorial (- n 1 )))))
(format t "~a" (factorial 5 ))
(defun factorial-iterative (n )
(do ((i 2 (1 + i))
(result 1 (* result i)))
((> i n) result)))52 How interviewers ask it “Show me fibonacci in Lisp — write it out and explain each step as you go.”
Coding Lisp
Quick answer Calculate Fibonacci using recursion, iteration, or memoization.
Recursive : (if (<= n 1) n (+ (fib (- n 1)) (fib (- n 2))))Iterative : do loopMemoization : memoize LispCopy
(defun fibonacci (n )
(if (<= n 1 )
n
(+ (fibonacci (- n 1 )) (fibonacci (- n 2 )))))
(format t "~a" (fibonacci 8 ))
(defun fibonacci-iterative (n )
(do ((a 0 b)
(b 1 (+ a b))
(i 2 (1 + i)))
((> i n) b)))53 How interviewers ask it “Show me fizzBuzz in Lisp — write it out and explain each step as you go.”
Coding Lisp
Quick answer FizzBuzz using cond for modular arithmetic.
When expression : condOrder : Check 15 firstRange : dotimes LispCopy
(defun fizzbuzz (n )
(dotimes (i n)
(let ((num (1 + i)))
(cond
((zerop (mod num 15 )) (format t "FizzBuzz" ))
((zerop (mod num 3 )) (format t "Fizz" ))
((zerop (mod num 5 )) (format t "Buzz" ))
(t (format t "~a" num))))))
(fizzbuzz 15 )54 How interviewers ask it “Coding-round task — find missing number in Lisp. Explain your approach before you write the code.”
Coding Lisp
Quick answer Find missing number using formula or XOR.
Formula : (- total sum)XOR method : XOR all numbers and indicesEdge cases : Empty array LispCopy
(defun find-missing (arr )
(let* ((n (1 + (length arr)))
(total (/ (* n (1 + n)) 2 ))
(sum (reduce #'+ arr)))
(- total sum)))
(format t "~a" (find-missing '(1 2 4 5 6 ))) 55 How interviewers ask it “Live coding: Find duplicates in Lisp. Talk me through your approach first.”
Coding Lisp
Quick answer Find duplicates using a set or hash table.
Set method : Track seen elementsFilter : remove-ifGroup by : group-by simulation LispCopy
(defun find-duplicates (arr )
(let ((seen '())
(duplicates '()))
(dolist (item arr)
(if (member item seen)
(push item duplicates)
(push item seen)))
duplicates))
(format t "~a" (find-duplicates '(1 2 3 2 4 3 ))) 56 How interviewers ask it “Can you sum of array in Lisp? Then walk me through the edge cases you would test.”
Coding Lisp
Quick answer Calculate sum using reduce or manual iteration.
Built-in : (reduce #'+ arr)Manual : dolistEmpty array : Returns 0 LispCopy
(defun sum-array (arr )
(reduce #'+ arr))
(format t "~a" (sum-array '(1 2 3 4 5 )))
(defun sum-array-manual (arr )
(let ((sum 0 ))
(dolist (num arr)
(incf sum num))
sum))57 How interviewers ask it “Show me average of array in Lisp — write it out and explain each step as you go.”
Coding Lisp
Quick answer Calculate average using sum divided by length.
Method : (/ (reduce #'+ arr) (length arr))Empty array : Handle with if checkPrecision : Returns rational LispCopy
(defun average-array (arr )
(/ (reduce #'+ arr) (length arr)))
(format t "~a" (average-array '(1 2 3 4 5 )))
(defun average-array-manual (arr )
(/ (sum-array-manual arr) (length arr)))58 How interviewers ask it “Live coding: Sort array ascending in Lisp. Talk me through your approach first.”
Coding Lisp
Quick answer Sort using sort with #'< .
Sort using sort with #'<.
Non-mutating : (sort (copy-seq arr) #'<)Mutating : (sort arr #'<)Complexity : O(n log n) LispCopy
(defun sort-ascending (arr )
(sort (copy-seq arr) #'<))
(format t "~a" (sort-ascending '(5 2 8 1 9 )))
(defun sort-ascending-in-place (arr )
(sort arr #'<))59 How interviewers ask it “Live coding: Sort array descending in Lisp. Talk me through your approach first.”
Coding Lisp
Quick answer Sort descending using sort with #'> .
Sort descending using sort with #'>.
Non-mutating : (sort (copy-seq arr) #'>)Mutating : (sort arr #'>)Complexity : O(n log n) LispCopy
(defun sort-descending (arr )
(sort (copy-seq arr) #'>))
(format t "~a" (sort-descending '(5 2 8 1 9 )))
(defun sort-descending-in-place (arr )
(sort arr #'>))60 How interviewers ask it “Coding-round task — flatten nested array in Lisp. Explain your approach before you write the code.”
Coding Lisp
Quick answer Flatten using recursion or mapcan.
Recursive : Check if listpmapcan : (mapcan #'flatten-array arr)Complexity : O(n) time LispCopy
(defun flatten-array (arr )
(cond
((null arr) nil )
((listp (car arr))
(append (flatten-array (car arr))
(flatten-array (cdr arr))))
(t (cons (car arr) (flatten-array (cdr arr))))))
(format t "~a" (flatten-array '(1 (2 (3 4 ) 5 ) 6 )))
(defun flatten-array-recursive (arr )
(if (atom arr)
(list arr)
(mapcan #'flatten-array-recursive arr)))61 How interviewers ask it “Show me chunk array in Lisp — write it out and explain each step as you go.”
Coding Lisp
Quick answer Split array into chunks using loop with by.
Method : (loop for i from 0 by size ...)Subseq : (subseq arr i (min (+ i size) ...))Use case : Batch processing LispCopy
(defun chunk-array (arr size)
(loop for i from 0 below (length arr) by size
collect (subseq arr i (min (+ i size) (length arr)))))
(format t "~a" (chunk-array '(1 2 3 4 5 6 ) 2 ))
(defun chunk-array-manual (arr size)
(let ((result '()))
(do ((i 0 (+ i size)))
((>= i (length arr)))
(push (subseq arr i (min (+ i size) (length arr))) result))
(reverse result)))62 How interviewers ask it “Show me binary search in Lisp — write it out and explain each step as you go.”
Coding Lisp
Quick answer Binary search on sorted array using manual implementation.
Manual : While loop with left/right pointersTime : O(log n)Requirement : Array must be sorted LispCopy
(defun binary-search (arr target)
(let ((left 0 )
(right (1 - (length arr))))
(loop while (<= left right)
do (let ((mid (floor (+ left right) 2 )))
(cond
((= (nth mid arr) target) (return mid))
((< (nth mid arr) target) (setf left (1 + mid)))
(t (setf right (1 - mid))))))
-1 ))
(format t "~a" (binary-search '(1 2 3 4 5 6 7 ) 5 ))
(defun binary-search-built-in (arr target)
(position target arr :test #'<))63 How interviewers ask it “Show me quick sort in Lisp — write it out and explain each step as you go.”
Coding Lisp
Quick answer Quick sort using pivot-based partitioning.
Algorithm : Choose pivot, partition, recurseTime : O(n log n) averageImplementation : Functional style LispCopy
(defun quick-sort (arr )
(if (<= (length arr) 1 )
arr
(let* ((pivot (car arr))
(rest (cdr arr))
(left (remove-if-not (lambda (x ) (< x pivot)) rest))
(right (remove-if (lambda (x ) (< x pivot)) rest)))
(append (quick-sort left) (list pivot) (quick-sort right)))))
(format t "~a" (quick-sort '(5 3 8 4 2 7 1 6 )))64 How interviewers ask it “Coding-round task — merge sort in Lisp. Explain your approach before you write the code.”
Coding Lisp
Quick answer Merge sort using divide-and-conquer.
Algorithm : Divide, sort, mergeTime : O(n log n)Space : O(n) auxiliary space LispCopy
(defun merge-sort (arr )
(if (<= (length arr) 1 )
arr
(let* ((mid (floor (length arr) 2 ))
(left (subseq arr 0 mid))
(right (subseq arr mid)))
(merge-lists (merge-sort left) (merge-sort right)))))
(defun merge-lists (left right)
(cond
((null left) right)
((null right) left)
((<= (car left) (car right))
(cons (car left) (merge-lists (cdr left) right)))
(t (cons (car right) (merge-lists left (cdr right))))))65 How interviewers ask it “Show me bubble sort in Lisp — write it out and explain each step as you go.”
Coding Lisp
Quick answer Bubble sort with early termination.
Algorithm : Compare adjacent, swapTime : O(n²) worst caseOptimization : Stop if no swaps LispCopy
(defun bubble-sort (arr )
(let ((sorted (copy-seq arr)))
(do ((i 0 (1 + i)))
((= i (1 - (length sorted))))
(do ((j 0 (1 + j)))
((= j (- (length sorted) 1 i)))
(when (> (nth j sorted) (nth (1 + j) sorted))
(rotatef (nth j sorted) (nth (1 + j) sorted)))))
sorted))
(defun bubble-sort-optimized (arr )
(let ((sorted (copy-seq arr)))
(do ((i 0 (1 + i)))
((= i (1 - (length sorted))))
(let ((swapped nil ))
(do ((j 0 (1 + j)))
((= j (- (length sorted) 1 i)))
(when (> (nth j sorted) (nth (1 + j) sorted))
(rotatef (nth j sorted) (nth (1 + j) sorted))
(setf swapped t )))
(unless swapped (return sorted))))
sorted))66 How interviewers ask it “Show me intersection of arrays in Lisp — write it out and explain each step as you go.”
Coding Lisp
Quick answer Find common elements using remove-if-not or hash set.
Filter : (remove-if-not (lambda (x) (member x arr2)) arr1)Set : make-hash-tableComplexity : O(n²) or O(n) LispCopy
(defun intersection-arrays (arr1 arr2)
(remove-if-not (lambda (x ) (member x arr2)) arr1))
(format t "~a" (intersection-arrays '(1 2 3 4 ) '(3 4 5 6 )))
(defun intersection-set (arr1 arr2)
(let ((set2 (make-hash-table )))
(dolist (item arr2)
(setf (gethash item set2) t ))
(remove-if-not (lambda (x ) (gethash x set2)) arr1)))67 How interviewers ask it “Show me union of arrays in Lisp — write it out and explain each step as you go.”
Coding Lisp
Quick answer Combine arrays with unique elements using remove-duplicates.
Method : (remove-duplicates (append arr1 arr2))Set : make-hash-tableComplexity : O(n log n) LispCopy
(defun union-arrays (arr1 arr2)
(remove-duplicates (append arr1 arr2)))
(format t "~a" (union-arrays '(1 2 3 ) '(3 4 5 )))
(defun union-set (arr1 arr2)
(remove-duplicates (append arr1 arr2)))Coding Lisp
Quick answer Find elements in first array not in second.
Difference : (remove-if (lambda (x) (member x arr2)) arr1)Symmetric : append differencesSet : Use hash set for efficiency LispCopy
(defun difference-arrays (arr1 arr2)
(remove-if (lambda (x ) (member x arr2)) arr1))
(format t "~a" (difference-arrays '(1 2 3 4 ) '(3 4 5 6 )))
(defun symmetric-difference (arr1 arr2)
(append (difference-arrays arr1 arr2)
(difference-arrays arr2 arr1)))69 How interviewers ask it “Can you group by property in Lisp? Then walk me through the edge cases you would test.”
Coding Lisp
Quick answer Group objects by property using hash tables.
Method : make-hash-tableGrouping : push items into groupsComplexity : O(n) time LispCopy
(defun group-by-property (items key)
(let ((groups (make-hash-table :test 'equal)))
(dolist (item items)
(let ((key-value
(if (equal key "type" )
(type item)
(name item))))
(push item (gethash key-value groups))))
groups))
(defstruct item type name)
(defparameter *data*
(list (make-item :type "fruit" :name "apple" )
(make-item :type "fruit" :name "banana" )
(make-item :type "veg" :name "carrot" )))
(defun print-groups (groups )
(maphash (lambda (key value)
(format t "~a: ~a" key value))
groups))70 How interviewers ask it “Live coding: Deep clone object in Lisp. Talk me through your approach first.”
Coding Lisp
Quick answer Deep clone by recursively copying structures.
Method : cond for different typesLists : mapcarHash tables : maphash LispCopy
(defun deep-clone (obj )
(cond
((null obj) nil )
((atom obj) obj)
((listp obj) (mapcar #'deep-clone obj))
((hash-table-p obj)
(let ((new (make-hash-table :test (hash-table-test obj))))
(maphash (lambda (key value)
(setf (gethash key new) (deep-clone value)))
obj)
new))
(t obj)))
(defstruct user name address)
(defstruct address city zip)
(defparameter *original*
(make-user :name "Alice"
:address (make-address :city "NYC" :zip "10001" )))
(defparameter *cloned* (deep-clone *original* ))71 How interviewers ask it “Show me immutable update in Lisp — write it out and explain each step as you go.”
Coding Lisp
Quick answer Perform immutable updates on nested alists.
Method : acons for updatesPath : Dot notation for nested accessUse case : Functional programming LispCopy
(defun update-immutable (obj path value)
(let ((parts (split-string path "." )))
(if (= (length parts) 1 )
(acons (car parts) value obj)
(let* ((first (car parts))
(rest (concatenate 'string (cdr parts) "." ))
(nested (cdr (assoc first obj))))
(acons first
(update-immutable nested rest value)
obj)))))
(defparameter *state* '((user (name "Alice" ) (age 25 ))))
(defparameter *new-state* (update-immutable *state* "user.age" 26 ))72 How interviewers ask it “Show me pipe function in Lisp — write it out and explain each step as you go.”
Coding Lisp
Quick answer Pipe composes functions from left to right.
Method : (pipe fns...)Implementation : dolist with funcallDirection : Left to right LispCopy
(defun pipe (&rest fns)
(lambda (value )
(let ((result value))
(dolist (fn fns)
(setf result (funcall fn result)))
result)))
(defun double (x ) (* x 2 ))
(defun add-ten (x ) (+ x 10 ))
(defun square (x ) (* x x))
(defparameter *process* (pipe #'double #'add-ten #'square))
(format t "~a" (funcall *process* 5 )) 73 How interviewers ask it “Show me compose function in Lisp — write it out and explain each step as you go.”
Coding Lisp
Quick answer Compose functions from right to left.
Method : (compose fns...)Implementation : dolist with funcallDirection : Right to left LispCopy
(defun compose (&rest fns)
(lambda (value )
(let ((result value))
(dolist (fn (reverse fns))
(setf result (funcall fn result)))
result)))
(defparameter *process2* (compose #'square #'add-ten #'double))
(format t "~a" (funcall *process2* 5 )) 74 How interviewers ask it “Show me memoization in Lisp — write it out and explain each step as you go.”
Coding Lisp
Quick answer Cache function results based on arguments.
Method : make-hash-tableKey : Arguments as keyTrade-off : Memory for speed LispCopy
(defun memoize (fn )
(let ((cache (make-hash-table :test 'equal)))
(lambda (arg )
(multiple-value-bind (value found) (gethash arg cache)
(if found
value
(let ((result (funcall fn arg)))
(setf (gethash arg cache) result)
result))))))
(defvar *fibonacci-memo*
(memoize (lambda (n )
(if (<= n 1 )
n
(+ (funcall *fibonacci-memo* (- n 1 ))
(funcall *fibonacci-memo* (- n 2 )))))))
(format t "~a" (funcall *fibonacci-memo* 10 ))75 How interviewers ask it “Show me once function in Lisp — write it out and explain each step as you go.”
Coding Lisp
Quick answer Ensure a function is called only once.
Method : Use flag and closureImplementation : Track if calledUse case : Initialization LispCopy
(defun once (fn )
(let ((called nil )
(result nil ))
(lambda ()
(unless called
(setf called t )
(setf result (funcall fn)))
result)))
(defparameter *initialize*
(once (lambda ()
(format t "Initialized" )
'(id 1 name "App" ))))
(funcall *initialize* )
(funcall *initialize* ) 76 How interviewers ask it “Live coding: Debounce with leading edge in Lisp. Talk me through your approach first.”
Coding Lisp
Quick answer Debounce with leading edge executes immediately then waits.
Method : Track last call timeImplementation : last-call and timerUse case : Save actions, API calls LispCopy
(defun debounce-leading (delay-ms fn)
(let ((last-call 0 )
(timer nil ))
(lambda ()
(let ((now (/ (get-internal-real-time ) 1000 )))
(if (< (- now last-call) (/ delay-ms 1000 ))
(progn
(when timer
(sb-thread :terminate-thread timer))
(setf timer
(sb-thread :make-thread
(lambda ()
(sleep (/ delay-ms 1000 ))
(setf last-call (/ (get-internal-real-time ) 1000 ))
(funcall fn)))))
(progn
(setf last-call now)
(funcall fn)))))))77 How interviewers ask it “Can you throttle with leading edge in Lisp? Then walk me through the edge cases you would test.”
Coding Lisp
Quick answer Throttle with leading edge executes at most once per time period.
Method : Track last call timeImplementation : Check time differenceUse case : Scroll events LispCopy
(defun throttle-leading (delay-ms fn)
(let ((last-call 0 ))
(lambda ()
(let ((now (/ (get-internal-real-time ) 1000 )))
(when (>= (- now last-call) (/ delay-ms 1000 ))
(setf last-call now)
(funcall fn))))))78 How interviewers ask it “Can you deep equal in Lisp? Then walk me through the edge cases you would test.”
Coding Lisp
Quick answer Deep equality comparison for nested structures.
Method : Recursive comparisonLists : everyHash tables : maphash LispCopy
(defun deep-equal (obj1 obj2)
(cond
((eq obj1 obj2) t )
((or (null obj1) (null obj2)) nil )
((and (listp obj1) (listp obj2))
(and (= (length obj1) (length obj2))
(every #'deep-equal obj1 obj2)))
((and (hash-table-p obj1) (hash-table-p obj2))
(and (= (hash-table-count obj1) (hash-table-count obj2))
(maphash (lambda (key value)
(and (deep-equal value (gethash key obj2))
t ))
obj1)))
(t (equal obj1 obj2))))79 How interviewers ask it “Show me observable pattern in Lisp — write it out and explain each step as you go.”
Coding Lisp
Quick answer Observable pattern for event notification.
Observable : Maintains subscribersSubscribe : Add callbackNotify : Call all subscribers LispCopy
(defclass observable ()
((subscribers :initform '() :accessor subscribers)))
(defgeneric subscribe (observable callback))
(defgeneric notify (observable data))
(defmethod subscribe ((obs observable) callback)
(push callback (subscribers obs))
(lambda () (setf (subscribers obs)
(remove callback (subscribers obs)))))
(defmethod notify ((obs observable) data)
(dolist (callback (subscribers obs))
(funcall callback data)))
(defparameter *obs* (make-instance 'observable))
(defparameter *unsubscribe*
(subscribe *obs* (lambda (data )
(format t "Received: ~a" data))))
(notify *obs* "Hello" )
(funcall *unsubscribe* )
(notify *obs* "World" ) 80 How interviewers ask it “Show me singleton pattern in Lisp — write it out and explain each step as you go.”
Coding Lisp
Quick answer Singleton pattern using closure.
Method : Closure with private stateThread-safe : Single-threadedGlobal access : Through variable LispCopy
(defvar *singleton*
(let ((data (make-hash-table )))
(lambda (command &rest args)
(case command
(:set (setf (gethash (car args) data) (cadr args)))
(:get (gethash (car args) data))
(t nil )))))
(funcall *singleton* :set "name" "Alice" )
(funcall *singleton* :get "name" ) 81 How interviewers ask it “Show me factory pattern in Lisp — write it out and explain each step as you go.”
Coding Lisp
Quick answer Factory pattern using functions.
Method : create-user functionBenefits : Decouples creationClasses : CLOS classes LispCopy
(defclass user () ())
(defclass admin (user )
((name :initarg :name :accessor name)))
(defclass guest (user )
((name :initarg :name :accessor name)))
(defclass regular-user (user )
((name :initarg :name :accessor name)))
(defun create-user (type name)
(case type
(:admin (make-instance 'admin :name name))
(:guest (make-instance 'guest :name name))
(t (make-instance 'regular-user :name name))))
(create-user :admin "Alice" )82 How interviewers ask it “Show me strategy pattern in Lisp — write it out and explain each step as you go.”
Coding Lisp
Quick answer Strategy pattern using generic functions.
Interface : defgenericContext : Uses strategyBenefits : Runtime switching LispCopy
(defgeneric pay (strategy amount))
(defclass credit-card-strategy () ())
(defclass paypal-strategy () ())
(defclass crypto-strategy () ())
(defmethod pay ((strategy credit-card-strategy) amount)
(format t "Paid $~a with Credit Card" amount))
(defmethod pay ((strategy paypal-strategy) amount)
(format t "Paid $~a with PayPal" amount))
(defmethod pay ((strategy crypto-strategy) amount)
(format t "Paid $~a with Crypto" amount))
(defclass payment-context ()
((strategy :initarg :strategy :accessor strategy)))
(defgeneric execute-payment (context amount))
(defmethod execute-payment ((context payment-context) amount)
(pay (strategy context) amount))
(defparameter *context*
(make-instance 'payment-context :strategy (make-instance 'credit-card-strategy)))
(execute-payment *context* 100 )
(setf (strategy *context* ) (make-instance 'paypal-strategy))
(execute-payment *context* 50 )83 How interviewers ask it “Show me observer pattern in Lisp — write it out and explain each step as you go.”
Coding Lisp
Quick answer Observer pattern using CLOS.
Subject : Maintains observersObserver : Receives updatesBenefits : Loose coupling LispCopy
(defclass observer ()
())
(defgeneric update (observer data))
(defclass subject ()
((observers :initform '() :accessor observers)
(state :initform "" :accessor state)))
(defmethod set-state ((subj subject) new-state)
(setf (state subj) new-state)
(notify-observers subj))
(defmethod attach ((subj subject) (obs observer))
(push obs (observers subj)))
(defmethod detach ((subj subject) (obs observer))
(setf (observers subj) (remove obs (observers subj))))
(defmethod notify-observers ((subj subject))
(dolist (obs (observers subj))
(update obs (state subj))))
(defclass concrete-observer ()
((name :initarg :name :accessor name)))
(defmethod update ((obs concrete-observer) data)
(format t "~a received: ~a" (name obs) data))
(defparameter *subject* (make-instance 'subject))
(defparameter *observer1* (make-instance 'concrete-observer :name "Observer1" ))
(defparameter *observer2* (make-instance 'concrete-observer :name "Observer2" ))
(attach *subject* *observer1* )
(attach *subject* *observer2* )
(set-state *subject* "Hello World" )84 How interviewers ask it “Show me decorator pattern in Lisp — write it out and explain each step as you go.”
Coding Lisp
Quick answer Decorator pattern using wrapper functions.
Component : Base classDecorator : Wraps componentBenefits : Flexible extension LispCopy
(defclass coffee ()
((cost :initarg :cost :accessor cost)
(description :initarg :description :accessor description)))
(defun milk-decorator (coffee )
(make-instance 'coffee
:cost (+ (cost coffee) 2.0 )
:description (concatenate 'string (description coffee) ", Milk" )))
(defun sugar-decorator (coffee )
(make-instance 'coffee
:cost (+ (cost coffee) 1.0 )
:description (concatenate 'string (description coffee) ", Sugar" )))
(defparameter *coffee* (make-instance 'coffee :cost 5.0 :description "Coffee" ))
(setf *coffee* (milk-decorator *coffee* ))
(setf *coffee* (sugar-decorator *coffee* ))
(format t "~a" (description *coffee* ))
(format t "~a" (cost *coffee* )) 85 How interviewers ask it “Show me command pattern in Lisp — write it out and explain each step as you go.”
Coding Lisp
Quick answer Command pattern using classes.
Command : Encapsulates requestInvoker : Executes commandsBenefits : Undo/redo LispCopy
(defgeneric execute (command ))
(defgeneric undo (command ))
(defclass add-command ()
((receiver :initarg :receiver :accessor receiver)
(value :initarg :value :accessor value)))
(defmethod execute ((cmd add-command))
(push (value cmd) (receiver cmd)))
(defmethod undo ((cmd add-command))
(setf (receiver cmd)
(remove (value cmd) (receiver cmd))))
(defparameter *receiver* '(1 2 3 ))
(defparameter *cmd* (make-instance 'add-command :receiver *receiver* :value 4 ))
(execute *cmd* )
(format t "~a" *receiver* )
(undo *cmd* )
(format t "~a" *receiver* ) 86 How interviewers ask it “Show me memento pattern in Lisp — write it out and explain each step as you go.”
Coding Lisp
Quick answer Memento pattern for state restoration.
Originator : Creates/restores mementosMemento : Stores stateCaretaker : Manages mementos LispCopy
(defclass memento ()
((state :initarg :state :accessor state)))
(defclass originator ()
((state :initform "" :accessor state)))
(defmethod save-state ((obj originator))
(make-instance 'memento :state (state obj)))
(defmethod restore-state ((obj originator) (memento memento))
(setf (state obj) (state memento)))
(defclass caretaker ()
((mementos :initform '() :accessor mementos)))
(defmethod add-memento ((obj caretaker) memento)
(push memento (mementos obj)))
(defmethod get-memento ((obj caretaker) index)
(nth index (mementos obj)))
(defparameter *originator* (make-instance 'originator))
(defparameter *caretaker* (make-instance 'caretaker))
(setf (state *originator* ) "State 1" )
(add-memento *caretaker* (save-state *originator* ))
(setf (state *originator* ) "State 2" )
(add-memento *caretaker* (save-state *originator* ))
(setf (state *originator* ) "State 3" )
(restore-state *originator* (get-memento *caretaker* 0 ))
(format t "~a" (state *originator* )) 87 How interviewers ask it “Show me mediator pattern in Lisp — write it out and explain each step as you go.”
Coding Lisp
Quick answer Mediator pattern for centralized communication.
Mediator : Encapsulates communicationColleague : Communicates through mediatorBenefits : Loose coupling LispCopy
(defclass mediator ()
((colleagues :initform '() :accessor colleagues)))
(defmethod register ((med mediator) colleague)
(push colleague (colleagues med)))
(defmethod send-message ((med mediator) message sender)
(dolist (col (colleagues med))
(unless (eq col sender)
(receive-message col message))))
(defclass colleague ()
((name :initarg :name :accessor name)
(mediator :initarg :mediator :accessor mediator)))
(defmethod initialize-instance :after ((col colleague) &key )
(register (mediator col) col))
(defmethod send-message ((col colleague) message)
(send-message (mediator col) message col))
(defmethod receive-message ((col colleague) message)
(format t "~a received: ~a" (name col) message))
(defparameter *mediator* (make-instance 'mediator))
(defparameter *alice* (make-instance 'colleague :name "Alice" :mediator *mediator* ))
(defparameter *bob* (make-instance 'colleague :name "Bob" :mediator *mediator* ))
(send-message *alice* "Hello Bob!" )88 How interviewers ask it “Show me chain of Responsibility in Lisp — write it out and explain each step as you go.”
Coding Lisp
Quick answer Chain of Responsibility using classes.
Handler : Processes or forwardsChain : Linked list of handlersBenefits : Decoupling LispCopy
(defclass handler ()
((next-handler :initform nil :accessor next-handler)))
(defgeneric set-next (handler next))
(defgeneric handle (handler request))
(defmethod set-next ((handler handler) next)
(setf (next-handler handler) next)
next)
(defclass auth-handler (handler )
())
(defmethod handle ((handler auth-handler) request)
(if (getf request :token )
(progn
(format t "Authentication passed" )
(let ((next (next-handler handler)))
(when next (handle next request))))
(format t "Authentication failed" )))
(defclass logger-handler (handler )
())
(defmethod handle ((handler logger-handler) request)
(format t "Logging request: ~a" (getf request :url ))
(let ((next (next-handler handler)))
(when next (handle next request))))
(defparameter *auth* (make-instance 'auth-handler))
(defparameter *logger* (make-instance 'logger-handler))
(set-next *auth* *logger* )
(handle *auth* '(:token "valid" :url "/api" ))89 How interviewers ask it “Show me state pattern in Lisp — write it out and explain each step as you go.”
Coding Lisp
Quick answer State pattern using classes.
Context : Maintains stateState : Defines behaviorBenefits : Clean state management LispCopy
(defgeneric handle-state (state ))
(defclass ready-state ()
())
(defclass processing-state ()
())
(defclass completed-state ()
())
(defmethod handle-state ((state ready-state))
(format t "Ready: Waiting for input" ))
(defmethod handle-state ((state processing-state))
(format t "Processing: Working on task" ))
(defmethod handle-state ((state completed-state))
(format t "Completed: Task finished" ))
(defclass context ()
((state :initform (make-instance 'ready-state)
:accessor state)))
(defmethod request ((ctx context))
(handle-state (state ctx)))
(defparameter *context* (make-instance 'context))
(request *context* )
(setf (state *context* ) (make-instance 'processing-state))
(request *context* )
(setf (state *context* ) (make-instance 'completed-state))
(request *context* ) 90 How interviewers ask it “Show me proxy pattern in Lisp — write it out and explain each step as you go.”
Coding Lisp
Quick answer Proxy pattern using classes.
Subject : Real objectProxy : Controls accessBenefits : Access control LispCopy
(defclass real-subject ()
())
(defmethod request ((obj real-subject))
(format t "RealSubject: Handling request" ))
(defclass proxy ()
((real-subject :initform nil :accessor real-subject)))
(defmethod request ((obj proxy))
(when (check-access obj)
(unless (real-subject obj)
(setf (real-subject obj) (make-instance 'real-subject)))
(request (real-subject obj))
(log-access obj)))
(defmethod check-access ((obj proxy))
(format t "Proxy: Checking access" )
t )
(defmethod log-access ((obj proxy))
(format t "Proxy: Logging access" ))
(defparameter *proxy* (make-instance 'proxy))
(request *proxy* )91 How interviewers ask it “Show me flyweight pattern in Lisp — write it out and explain each step as you go.”
Coding Lisp
Quick answer Flyweight pattern for sharing objects.
Flyweight : Shared objectFactory : Manages flyweightsBenefits : Memory optimization LispCopy
(defclass flyweight ()
((shared-state :initarg :shared-state :accessor shared-state)))
(defmethod operation ((obj flyweight) unique-state)
(format t "Shared: ~a, Unique: ~a"
(shared-state obj) unique-state))
(defclass flyweight-factory ()
((flyweights :initform (make-hash-table :test 'equal)
:accessor flyweights)))
(defmethod get-flyweight ((factory flyweight-factory) shared-state)
(or (gethash shared-state (flyweights factory))
(setf (gethash shared-state (flyweights factory))
(make-instance 'flyweight :shared-state shared-state))))
(defparameter *factory* (make-instance 'flyweight-factory))
(defparameter *fw1* (get-flyweight *factory* "state1" ))
(defparameter *fw2* (get-flyweight *factory* "state1" ))
(defparameter *fw3* (get-flyweight *factory* "state2" ))
(operation *fw1* "unique1" )
(operation *fw2* "unique2" )
(operation *fw3* "unique3" )92 How interviewers ask it “Show me bridge pattern in Lisp — write it out and explain each step as you go.”
Coding Lisp
Quick answer Bridge pattern using CLOS.
Abstraction : High-level interfaceImplementation : Low-level operationsBenefits : Separation of concerns LispCopy
(defgeneric operation-impl (impl ))
(defclass concrete-implementation-a ()
())
(defmethod operation-impl ((impl concrete-implementation-a))
(format t "ConcreteImplementationA: Operation" ))
(defclass concrete-implementation-b ()
())
(defmethod operation-impl ((impl concrete-implementation-b))
(format t "ConcreteImplementationB: Operation" ))
(defclass abstraction ()
((impl :initarg :impl :accessor impl)))
(defmethod operation ((abst abstraction))
(format t "Abstraction: Additional logic" )
(operation-impl (impl abst)))
(defparameter *impl-a* (make-instance 'concrete-implementation-a))
(defparameter *impl-b* (make-instance 'concrete-implementation-b))
(defparameter *abstraction1* (make-instance 'abstraction :impl *impl-a* ))
(defparameter *abstraction2* (make-instance 'abstraction :impl *impl-b* ))
(operation *abstraction1* )
(operation *abstraction2* )93 How interviewers ask it “Show me adapter pattern in Lisp — write it out and explain each step as you go.”
Coding Lisp
Quick answer Adapter pattern using wrapper classes.
Target : Expected interfaceAdaptee : Existing interfaceAdapter : Bridges interfaces LispCopy
(defclass target ()
())
(defmethod request ((obj target))
(format t "Target: Request" ))
(defclass adaptee ()
())
(defmethod specific-request ((obj adaptee))
(format t "Adaptee: Specific Request" ))
(defclass adapter ()
((adaptee :initarg :adaptee :accessor adaptee)))
(defmethod request ((obj adapter))
(specific-request (adaptee obj)))
(defparameter *adaptee* (make-instance 'adaptee))
(defparameter *adapter* (make-instance 'adapter :adaptee *adaptee* ))
(request *adapter* )94 How interviewers ask it “Show me facade pattern in Lisp — write it out and explain each step as you go.”
Coding Lisp
Quick answer Facade pattern using composition.
Facade : Simplified interfaceSubsystem : Complex componentsBenefits : Simplified interface LispCopy
(defclass subsystem-a ()
())
(defmethod operation-a ((obj subsystem-a))
(format t "SubsystemA: Operation" ))
(defclass subsystem-b ()
())
(defmethod operation-b ((obj subsystem-b))
(format t "SubsystemB: Operation" ))
(defclass facade ()
((subsystem-a :initform (make-instance 'subsystem-a) :accessor subsystem-a)
(subsystem-b :initform (make-instance 'subsystem-b) :accessor subsystem-b)))
(defmethod operation ((obj facade))
(operation-a (subsystem-a obj))
(operation-b (subsystem-b obj))
(format t "Facade: Complex operation" ))
(defparameter *facade* (make-instance 'facade))
(operation *facade* )95 How interviewers ask it “Show me composite pattern in Lisp — write it out and explain each step as you go.”
Coding Lisp
Quick answer Composite pattern using classes.
Component : Interface for allLeaf : Individual objectComposite : Container LispCopy
(defgeneric operation (component ))
(defclass leaf ()
((name :initarg :name :accessor name)))
(defmethod operation ((obj leaf))
(format t "Leaf ~a: Operation" (name obj)))
(defclass composite ()
((name :initarg :name :accessor name)
(children :initform '() :accessor children)))
(defmethod add ((obj composite) component)
(push component (children obj)))
(defmethod remove ((obj composite) component)
(setf (children obj) (remove component (children obj))))
(defmethod operation ((obj composite))
(format t "Composite ~a: Operation" (name obj))
(dolist (child (children obj))
(operation child)))
(defparameter *leaf1* (make-instance 'leaf :name "A" ))
(defparameter *leaf2* (make-instance 'leaf :name "B" ))
(defparameter *composite* (make-instance 'composite :name "Root" ))
(add *composite* *leaf1* )
(add *composite* *leaf2* )
(operation *composite* )96 How interviewers ask it “Show me visitor pattern in Lisp — write it out and explain each step as you go.”
Coding Lisp
Quick answer Visitor pattern using generic functions.
Visitor : Defines operationsElement : Accepts visitorsBenefits : Adding operations without modifying LispCopy
(defgeneric accept (element visitor))
(defgeneric visit (visitor element))
(defclass element-a ()
())
(defmethod accept ((obj element-a) visitor)
(visit visitor obj))
(defclass element-b ()
())
(defmethod accept ((obj element-b) visitor)
(visit visitor obj))
(defclass visitor ()
())
(defmethod visit ((visitor visitor) (element element-a))
(format t "Visiting ElementA" ))
(defmethod visit ((visitor visitor) (element element-b))
(format t "Visiting ElementB" ))
(defparameter *visitor* (make-instance 'visitor))
(defparameter *element-a* (make-instance 'element-a))
(defparameter *element-b* (make-instance 'element-b))
(accept *element-a* *visitor* )
(accept *element-b* *visitor* )97 How interviewers ask it “Show me iterator pattern in Lisp — write it out and explain each step as you go.”
Coding Lisp
Quick answer Iterator pattern using classes.
Iterator : Traverses collectionAggregate : Creates iteratorBenefits : Uniform traversal LispCopy
(defclass iterator ()
((collection :initarg :collection :accessor collection)
(index :initform 0 :accessor index)))
(defgeneric next (iterator ))
(defgeneric has-next (iterator ))
(defmethod next ((it iterator))
(if (has-next it)
(let ((result (nth (index it) (collection it))))
(incf (index it))
result)
nil ))
(defmethod has-next ((it iterator))
(< (index it) (length (collection it))))
(defclass custom-collection ()
((items :initform '() :accessor items)))
(defmethod add ((col custom-collection) item)
(push item (items col)))
(defmethod get-iterator ((col custom-collection))
(make-instance 'iterator :collection (items col)))
(defparameter *collection* (make-instance 'custom-collection))
(add *collection* "A" )
(add *collection* "B" )
(add *collection* "C" )
(defparameter *iterator* (get-iterator *collection* ))
(loop while (has-next *iterator* )
do (format t "~a" (next *iterator* )))98 How interviewers ask it “Show me template Method pattern in Lisp — write it out and explain each step as you go.”
Coding Lisp
Quick answer Template Method using generic functions.
AbstractClass : Defines templateConcreteClass : Implements stepsBenefits : Code reuse LispCopy
(defclass abstract-class ()
())
(defgeneric template-method (obj ))
(defgeneric step1 (obj ))
(defgeneric step2 (obj ))
(defgeneric step3 (obj ))
(defmethod template-method ((obj abstract-class))
(step1 obj)
(step2 obj)
(step3 obj))
(defmethod step1 ((obj abstract-class))
(format t "Step 1" ))
(defmethod step3 ((obj abstract-class))
(format t "Step 3" ))
(defclass concrete-class (abstract-class )
())
(defmethod step2 ((obj concrete-class))
(format t "Concrete Step 2" ))
(defparameter *concrete* (make-instance 'concrete-class))
(template-method *concrete* )99 How interviewers ask it “Show me builder pattern in Lisp — write it out and explain each step as you go.”
Coding Lisp
Quick answer Builder pattern using classes.
Builder : Constructs partsDirector : Orchestrates constructionProduct : Constructed object LispCopy
(defclass product ()
((parts :initform '() :accessor parts)))
(defmethod add-part ((obj product) part)
(push part (parts obj)))
(defmethod list-parts ((obj product))
(format t "~a" (parts obj)))
(defclass builder ()
((product :initform (make-instance 'product) :accessor product)))
(defmethod reset ((obj builder))
(setf (parts (product obj)) '()))
(defmethod build-step-a ((obj builder))
(add-part (product obj) "Part A" ))
(defmethod build-step-b ((obj builder))
(add-part (product obj) "Part B" ))
(defmethod get-result ((obj builder))
(product obj))
(defclass director ()
((builder :initarg :builder :accessor builder)))
(defmethod build-minimal ((obj director))
(build-step-a (builder obj)))
(defmethod build-full ((obj director))
(build-step-a (builder obj))
(build-step-b (builder obj)))
(defparameter *builder* (make-instance 'builder))
(defparameter *director* (make-instance 'director :builder *builder* ))
(build-minimal *director* )
(defparameter *product* (get-result *builder* ))
(list-parts *product* )100 How interviewers ask it “Show me prototype pattern in Lisp — write it out and explain each step as you go.”
Coding Lisp
Quick answer Prototype pattern for cloning objects.
Prototype : Cloneable objectClone : Creates a copyBenefits : Performance LispCopy
(defclass prototype ()
((name :initarg :name :accessor name)
(nested :initarg :nested :accessor nested)))
(defmethod clone ((obj prototype))
(make-instance 'prototype
:name (name obj)
:nested (copy-list (nested obj))))
(defmethod deep-clone ((obj prototype))
(make-instance 'prototype
:name (name obj)
:nested (deep-copy (nested obj))))
(defun deep-copy (obj )
(cond
((null obj) nil )
((atom obj) obj)
((listp obj) (mapcar #'deep-copy obj))
((hash-table-p obj)
(let ((new (make-hash-table :test (hash-table-test obj))))
(maphash (lambda (key value)
(setf (gethash key new) (deep-copy value)))
obj)
new))
(t obj)))
(defparameter *original*
(make-instance 'prototype :name "Original" :nested '((value . 42 ))))
(defparameter *copy* (clone *original* ))
(setf (name *copy* ) "Copy" )
(setf (cdr (assoc 'value (nested *copy* ))) 99 )
(format t "~a" (name *original* ))
(format t "~a" (cdr (assoc 'value (nested *original* ))))
(defparameter *deep-copy* (deep-clone *original* ))
(setf (cdr (assoc 'value (nested *deep-copy* ))) 100 )
(format t "~a" (cdr (assoc 'value (nested *original* )))) Practise with the free Lisp quiz Multiple-choice questions with instant feedback. Takes about 10 minutes and shows exactly which concepts to revise.
Start the Lisp quiz →
Lisp interview FAQ What is Lisp programming language? Lisp is one of the oldest high-level programming languages known for its symbolic expression processing, functional programming approach, list manipulation, and powerful macro system.
What are S-expressions in Lisp? S-expressions (Symbolic Expressions) are the fundamental syntax structure in Lisp used to represent both code and data. They consist of atoms and lists enclosed in parentheses.
What is the difference between Common Lisp and Clojure? Common Lisp is a traditional Lisp dialect designed for general-purpose programming, while Clojure is a modern Lisp dialect that runs on the Java Virtual Machine and focuses on functional programming and concurrency.
What are macros in Lisp? Lisp macros allow developers to extend the language by transforming code before execution. They provide powerful metaprogramming capabilities.
What are atoms and lists in Lisp? Atoms are basic Lisp data elements such as numbers and symbols, while lists are collections of elements represented using parentheses.
What is recursion in Lisp? Recursion is a programming technique where a function calls itself to solve smaller versions of a problem. Lisp commonly uses recursion because of its list-processing capabilities.
What are lambda functions in Lisp? Lambda functions are anonymous functions in Lisp that allow developers to create temporary functions without naming them.
Why are Lisp interview questions important? Lisp interview questions test understanding of functional programming, recursion, symbolic computation, macros, data structures, and advanced programming concepts.
Do companies ask Lisp coding interview questions? Yes. Companies working with artificial intelligence, research systems, functional programming, and legacy enterprise applications may ask Lisp coding and conceptual interview questions.
How can I prepare for a Lisp interview? Practice Lisp syntax, S-expressions, recursion, list operations, lambda functions, macros, functional programming concepts, Common Lisp features, and real-world coding problems.
AK
Written and reviewed by Abhishek Kumar Founder, InterviewPitch · 10+ years in IT. Questions are collected from real interview rounds and refreshed regularly. Spotted an error?
Tell us .