Code is Data, Data is Code

A publication for Lisp Languages

Member-only story

Common Lisp’s DO loop

Gwang-Jin
Code is Data, Data is Code
8 min readDec 16, 2024

--

Photo by Tine Ivanič on Unsplash

The DO loop is the most general form of a loop in Common Lisp.

I want to go with you through the intricacies of this looping command, so that you can write a DO loop by yourself in future.

Loops have mostly variables, which have an initial value and get modified in every round of the loop.

In a normal DO loop, these variables are set and updated in parallel (they can’t see each other).

A very typical loop in C languages is the for loop.

C’s for loop

Let’s take a typical for loop in C and translate it into the DO loop in Common Lisp.

#include <stdio.h>

int main() {
// Loop from 1 to 10
for (int i = 1; i <= 10; i++) {
printf("The current value of i is: %d\n", i);
}

return 0;
}

The initial value for i is bound to i. Then, the exit condition i <= 10 is given, followed by the instruction how to modify i in every round: i++ which is i = i + 1 .
And then comes the instruction which should be executed for every round: To print the value of i.

General DO Loop Form

--

--

Gwang-Jin
Gwang-Jin

Written by Gwang-Jin

Data Scientist & Molecular Medicist - loving FP

Responses (2)