DEV Community

Cover image for Building a Four-Bar Linkage Mechanism Simulator in Haskell
Abolfazl Mohammadijoo
Abolfazl Mohammadijoo

Posted on

Building a Four-Bar Linkage Mechanism Simulator in Haskell

Most developers know Haskell as a language for functional programming, type safety, compilers, parsers, and beautiful mathematical abstractions.

But can Haskell also be used to build an interactive engineering simulator?

That was the motivation behind my project:

Four-Bar Mechanism Haskell Simulator

Repository:

https://github.com/mohammadijoo/Four-Bar-Mechanism-Haskell

This project is a browser-backed desktop-style GUI application written in Haskell. It visualizes, classifies, and animates a planar four-bar linkage mechanism, which is one of the most classical mechanisms in mechanical engineering, kinematics, and machine design.

The GUI is built with Threepenny-GUI, so the interface runs in a local browser window, while the mathematical model and mechanism logic remain written in Haskell.

For me, the interesting part was not only drawing a moving linkage. It was about connecting mechanism design theory, computational geometry, and functional programming in one small educational simulator.



What is a four-bar linkage?

A four-bar linkage is a closed-loop mechanical system made from four rigid links connected by four revolute joints.

In this project, the four links are:

Symbol Name Description
g Ground link Fixed distance between pivots A and B
a Input link Rotating link from A to moving pivot C
b Output link Link from fixed pivot B to moving pivot D
f Floating link / coupler Link connecting moving pivots C and D

The fixed pivots are placed at:

A=(0,0),B=(g,0) A = (0,0), \qquad B = (g,0)

The input link rotates by angle α\alpha . Therefore, point C can be computed directly as:

C=(acosα,;asinα) C = (a\cos\alpha,; a\sin\alpha)

Point D is more interesting.

It must satisfy two geometric distance constraints:

DC=f |D - C| = f
DB=b |D - B| = b

So the simulator solves the position of point D using a circle-intersection method.

One circle is centered at C with radius f.
The other circle is centered at B with radius b.

Where those two circles intersect, the mechanism can close.

That is the basic geometric heart of the simulator.


Why four-bar linkages matter

Four-bar mechanisms appear in many real mechanical systems.

Some examples include:

Application Role of the four-bar idea
Engines Converts rotating and oscillating motion
Suspension systems Guides constrained motion
Robotic grippers Creates controlled opening and closing paths
Pumps Converts rotary motion into reciprocating motion
Walking mechanisms Generates repeated leg-like motion
Windshield wipers Converts motor rotation into sweeping motion
Machine tools Produces repeatable constrained motion

A four-bar linkage is simple enough to understand visually, but rich enough to teach real mechanism design concepts.

That is why it appears so often in mechanical engineering and machine design courses.


Mobility of the mechanism

A planar mechanism can be analyzed using the Kutzbach-Grübler mobility equation.

M=3(n1)2j1j2 M = 3(n - 1) - 2j_1 - j_2

where:

Symbol Meaning
M Mobility / degrees of freedom
n Number of links
j1 Number of lower pairs, such as revolute joints
j2 Number of higher pairs

For an ideal planar four-bar linkage:

n=4,j1=4,j2=0 n = 4, \qquad j_1 = 4, \qquad j_2 = 0

Substituting these values gives:

M=3(41)2(4)0 M = 3(4 - 1) - 2(4) - 0
M=98=1 M = 9 - 8 = 1

So a four-bar linkage has exactly one degree of freedom.

This means that once the input angle is chosen, the rest of the linkage configuration is determined by the loop-closure constraints, except for the selected assembly branch.

That is a nice result: one input motion drives the whole mechanism.


The implemented geometric model

The simulator computes the mechanism position from the link lengths and the input angle.

First, the distance between B and C is calculated:

d=BC d = |B - C|

For the mechanism to close, the two circles must intersect. The assembly condition is:

fbdf+b |f - b| \le d \le f + b

If this condition is not satisfied, there is no real point D, and the mechanism cannot be assembled at that input angle.

When the condition is satisfied, there are usually two possible solutions for point D. These represent the two assembly branches of the mechanism.

In the GUI, the user can switch between these two branches using the Flip branch button or the F key.

This is one of the parts I like most about the project: the animation is not just a pre-drawn visual effect. The simulator actually solves the linkage geometry.


Grashof condition

One of the most important ideas in four-bar linkage design is the Grashof condition.

Let the four link lengths be sorted as:

spql s \le p \le q \le l

where s is the shortest link and l is the longest link.

The Grashof index is:

G=s+lpq G = s + l - p - q

The classification is:

Condition Meaning
G < 0 Grashof mechanism
G = 0 Change-point mechanism
G > 0 Non-Grashof mechanism

This matters because a Grashof mechanism usually has at least one link that can make a full rotation relative to the ground.

In practical terms, this helps answer an important design question:

Can the input link rotate continuously, or will it only rock back and forth?

That is exactly the kind of question a mechanism designer needs to answer early.


Validity index

The simulator also checks whether the mechanism is physically assemblable.

The validity index is:

V=lspq V = l - s - p - q

A valid four-bar mechanism must satisfy:

V0 V \le 0

If:

V>0 V > 0

then the longest link is longer than the sum of the other three links. In that case, the loop cannot close.

So the simulator reports not only the motion type, but also whether the chosen link lengths describe a valid mechanism.

This is useful because a random set of four link lengths does not always produce a real four-bar linkage.


Full linkage state classification

The simulator computes three excess values:

T1=g+fba T_1 = g + f - b - a
T2=b+gfa T_2 = b + g - f - a
T3=f+bga T_3 = f + b - g - a

The signs of these values help classify the detailed linkage state.

The GUI then displays the simplified motion type:

Classification Meaning
crank-crank Both relevant links can rotate fully
crank-rocker Input rotates fully, output rocks
rocker-crank Input rocks, output rotates fully
rocker-rocker Both links oscillate

This turns the project into more than a moving diagram. It becomes a small mechanism classification tool.


Why use Haskell?

Haskell is probably not the first language most people would choose for a mechanical simulator.

Python, MATLAB, C++, JavaScript, or Julia are more common choices for engineering applications.

But that is exactly why this project was interesting.

Haskell is very good at separating pure mathematical logic from side-effecting application code.

In this project, the mechanism model is separated into a pure Haskell module:

src/FourBar.hs
Enter fullscreen mode Exit fullscreen mode

This module contains the core mechanism logic, including:

Linkage
Pose
excesses
grashofIndex
validityIndex
classifyMotion
basicMotionState
solvePose
nearestValidAlpha
Enter fullscreen mode Exit fullscreen mode

The GUI and event loop are handled separately in:

app/Main.hs
Enter fullscreen mode Exit fullscreen mode

This separation is important.

The mechanism solver can later be reused in tests, command-line tools, notebooks, optimization programs, or even a web backend.

So Haskell helps keep the engineering model clean, testable, and reusable.

That is one of the main reasons I enjoyed building this project.


Threepenny-GUI and the browser-backed interface

The project uses Threepenny-GUI.

Threepenny-GUI allows a Haskell program to create an interface that is rendered in a web browser. The application starts a local GUI server, and the user opens:

http://127.0.0.1:8023
Enter fullscreen mode Exit fullscreen mode

The browser is the visual layer, but the application logic remains in Haskell.

The GUI includes:

Feature Description
Link sliders Change g, a, b, and f interactively
SVG drawing Renders the mechanism as scalable browser graphics
Play / Pause Starts and stops the animation
Flip branch Switches between the two assembly solutions
Reset Restores the default mechanism
Angle display Shows live alpha and beta values
Classification panel Shows Grashof, validity, and crank/rocker state
Keyboard controls Space, F, and R shortcuts

I like this architecture because it combines two worlds:

Haskellmechanism logic \text{Haskell} \rightarrow \text{mechanism logic}
Browser + SVGvisual interface \text{Browser + SVG} \rightarrow \text{visual interface}

Threepenny-GUI acts as the bridge between them.


SVG visualization

The mechanism is rendered using SVG.

SVG is a good fit for this kind of project because it is scalable, clean, and works naturally inside a browser interface.

The simulator draws:

  • fixed pivots
  • moving pivots
  • links
  • labels
  • angle arcs
  • the current linkage configuration

Because the GUI is browser-rendered, the interface can use HTML, CSS, fonts, and SVG while still keeping the engineering logic in Haskell.

The result is a simple but effective architecture:

Pure Haskell solver+Threepenny-GUI+SVG rendering \text{Pure Haskell solver} + \text{Threepenny-GUI} + \text{SVG rendering}

Repository structure

The repository is organized like this:

Four-Bar-Mechanism-Haskell/
├── app/
│   └── Main.hs
├── src/
│   └── FourBar.hs
├── resources/
│   └── fonts/
│       └── Inter-Regular.ttf
├── fourbar-linkage-threepenny.cabal
├── README.md
├── LICENSE
└── .gitignore
Enter fullscreen mode Exit fullscreen mode

The most important files are:

src/FourBar.hs
app/Main.hs
Enter fullscreen mode Exit fullscreen mode

FourBar.hs contains the pure mechanism mathematics.

Main.hs builds the GUI, handles events, updates the state, and renders the current mechanism as SVG.

This structure makes the project easier to understand because the engineering model is not mixed directly into the interface code.


How to run the project

First, install Haskell using GHCup.

Then clone the repository:

git clone https://github.com/mohammadijoo/Four-Bar-Mechanism-Haskell.git
cd Four-Bar-Mechanism-Haskell
Enter fullscreen mode Exit fullscreen mode

Update Cabal:

cabal update
Enter fullscreen mode Exit fullscreen mode

Run the simulator:

cabal run fourbar-linkage-threepenny
Enter fullscreen mode Exit fullscreen mode

If the browser does not open automatically, open:

http://127.0.0.1:8023
Enter fullscreen mode Exit fullscreen mode

Controls

Control Action
Drag g slider Change ground link length
Drag a slider Change input link length
Drag b slider Change output link length
Drag f slider Change floating/coupler link length
Play / Pause Start or stop animation
Flip branch Switch assembly branch
Reset Restore default mechanism
Space Toggle Play / Pause
F Flip branch
R Reset

The sliders make the simulator useful for experimentation.

You can change link lengths and immediately see how the mechanism behavior changes.

That is helpful for learning because mechanism theory becomes visual.


What this project demonstrates

This project demonstrates several ideas at the same time:

Area What the project shows
Mechanical engineering Four-bar linkage geometry and classification
Kinematics Loop-closure constraints and assembly branches
Computational geometry Circle intersection for solving point D
Haskell programming Pure modeling separated from GUI code
GUI development Browser-backed interface with Threepenny-GUI
Visualization SVG-based scalable mechanism drawing

For me, the most useful lesson is that Haskell can be used for more than abstract examples.

It can also be used to build small, practical, interactive engineering tools.


Possible future improvements

Some future improvements could make the simulator even more useful:

  • Add coupler point tracing
  • Plot the coupler curve
  • Export motion data as CSV
  • Add velocity and acceleration analysis
  • Add transmission angle plots
  • Add mechanical advantage visualization
  • Add automated tests for mechanism classification
  • Package the app as a standalone desktop executable

The most interesting improvement would probably be coupler curve tracing.

Many real design problems ask:

What link lengths should I choose so that a point on the coupler follows a desired path?

Adding that feature would move the project from simulation toward mechanism synthesis.


Conclusion

The four-bar linkage is simple, but it contains many important engineering ideas.

With only four links and four revolute joints, it can produce rich motion patterns and useful mechanical transformations.

In this project, I used Haskell to model the mechanism, Threepenny-GUI to build the interface, and SVG to render the animation in a browser-backed desktop-style application.

The result is a small educational simulator that connects theory, geometry, and functional programming.

Repository:

https://github.com/mohammadijoo/Four-Bar-Mechanism-Haskell

Thanks for reading.

Top comments (0)