DEV Community

EstebanMarin
EstebanMarin

Posted on

Learning Physics with Functional Programming and Haskell

TL;DR; I gave a talk at LambdaConf 2025 this is a follow up post. Haskell Files -> GitHub. I'll post the video once I get it

Also, please, if you like the post and get curious, make sure to buy the book from Scott N. Walck

Image description

This talk is about objects and arrows that point to objects. And you will see a lot of that throughout the talk

Last year I learned that functional programming is a great tool to learn Physics, because it’s a great way to write math.

You see, Physics is expressed in the language of Math.
The relation of Math and code is now more present than ever.
Therefore, applying my debugging skills as a software developer, I was able to get a deep understanding of physics whilst writing code, which was a lot of fun, and I want to share the experience with you.

With this talk, I hope to explain Newton’s second law, describing the problem through types and writing math as code to help us compute functions. This is a new perspective on learning Functional Programming and/or Physics.

Image description

Haskell is one of the best tools for drawing objects and arrows!!!!

People do not see this as a graphical language, but I would like to show otherwise.
We will derive our code implementation magically by taking a math equation and transcribing it letter by letter into Haskell code.

But we will get types for free!! And this is mind-bending.

Code will not feel like code.

Image description

Describing our domain problem through types

Here we are just writing types in Haskell

We start with a wrapper over double for a Real number, I know, big assumption, but let’s carry on.

We also see a function definition and each time you see an -> I want you to think of a normal math function.

The one you would write on a piece of paper

Image description

Visually, the Haskell compiler is representing the following

Everything encoded as a Real number: acceleration, velocity, position and time.

The interesting question is: How to jump between the endpoints?

How do you go from a position function to a velocity function, and even more interesting, how do you come back?

The answer is arrows!! And in Haskell, that's a function.

Describing the type of function in this question, we can start implementing code.

Image description

Defining velocity as distance travel through time.

Rewriting the definition for smalls t

And limiting the delta T to cero

We will arrive to the instantaneous velocity
Once we have definition of instant velocity.

We can implement derivatives in Haskell

Image description

The code in haskell is a one to one mapping of the function you would write on a piece of paper.

This can also be python code too.

The real kick comes when the Haskell compiler infers the types, which come for free!!!

(first mind blow moment for me) Thinking of calculus through types

Image description

We see that derivative is a higher order function,

I never really thought about derivatives as HoF, but there you go.

Higher order functions can help us glue code nicely

contributing us to build a very complex model

Now what we have a derivative definition.

Let’s revisit the core question of our initial model

How from position/time measurements can we infer the particle velocity and acceleration?

That’s really the question.

The Haskell implementation is straightforward and very ergonomic, using point-free notation

Image description

The derivative function gives the ability to move clockwise in the model,

Image description

And this is very powerful.

But, How can we reverse the movement, like going counter-clockwise?

Like what’s an antiderivative?

Before answering what an antiderivative is:

Let’s explore an old idea idea that came even before derivatives.

It’s dividing something by parts and sum them all together to get an approximation of the whole.

Here we are stating that

the area under the function is the bounded integral of a function between A and B

Image description

Using equational reasoning:

Means that the bounded integral is the area under the function.

The intuition I want to present here is thinking of what’s left of the equal sign as the math object we want to represent

And to the right of the equal sign as the way we get there, more precisely the right side

Is a computation that we will give to the computer.

Lets see how calculating an area does it look in haskell

Image description

Let's start with the sum of rectangles of height f(t) times some delta t

Now we need a stream of rectangles that are evenly spaced

Using the midpoint rule we are going to sample f(t) here

Which, I believe is a very concise way of expressing the implementation of an integral

We are summing all rectangles from a to b at a midpoint rule.

Now that we have our definition of bounded integral

Let’s explore the types the haskell compiler provide us

Image description

Next we see that an integral can be either Analytical like we learn in highschool, or numerical.

We want to do numerical integrations, more precisely, we want the computer to handle the integration for us

On top we define Numerical integrations is a Type that Takes a function to integrate lower and upper bound

Returns a real number as a result

Coming back to the question of how to move clockwise and counterclockwise

Image description

We let the geniuses enter the stage and we will take their work for face value, for now.

Newton states that:

Derivatives and unbounded integrals are just part of the same.

One is the inverse of the other.

Derivatives and unbounded integrals are just part of the same.

Image description

Mathematically, the fundamental theorem of calculus is presented as:

Derivatives and Antiderivatives equate

The bounded integral of f(x) in the interval a through b

Equates as the Anti Derivative at b minus anti derivative at a.

Revisiting the intuition of moving terms around to the right so we can give the computer to compute

And the mathematical object to the left. Lets actually get the Antiderivative of any function by

Image description

Revisiting the intuition of moving terms around to the right so we can give the computer to compute

And the mathematical object to the left. Lets actually get the Antiderivative of any function by

The Antiderivative of F(x) is

An initial value F at b plus the bounded integral of the function

And we can do bounded integrals in haskell already!! NUMERICALLY!!!

Writing this code in haskell, or mapping the math as code

we now have a function that can anti-derivate any function

Again code does not feel like code and

Lets look and learn from the the types we get for free!!

Image description

The type of Anti derivative is …… surprise surprise

a higher order function!!! Like derivative, takes a function returns a function

And we will delegate that computation to the answer to the computer so we can numerically get a useful realtime answer

This means, therefore

Image description
We have now a cute model in haskell that can solve any Kinematic high school physics problem.

Recapping:

Everything encoded as a Real number, acceleration, velocity and position.

and we can go from them and back using derivatives and anti-derivates.

Now lets actually play around with our code and test it in real life

Imagine we go outside and let fall several objects measuring it position, time and mass. Which leads us to a function as show.

Image description

Could we make predictions about velocity and acceleration???

The answer is yes!

Image description

We make a derivative of a parabola,

which is a slope and that’s velocity

Deriving a slope gives us ….?

A constant!!

Image description

Imagine yourself doing this experiment/measurement for several months
varying the mass of the object, and arriving to the same acceleration constant!!!

This is another moment of Netwon’s brilliancy because the notices that the constant acceleration is part of a bigger picture

Newton claims again.

Force is proportional to the mass times the acceleration,
here acceleration show as a second derivate, implying a differential equation.

Image description

How is this new Force Object relates to our initial model? We will encode it in a Real number as the others

Newton created the scientific method by dissecting problems into parts, and then compose that
Into a more complex model.

We start with a simple version of the problem how does the model behaves in constant force?

Like for example a as falling apple

Image description

All consistent with what we measured in the lab so this is useful.

Lets get more creative with our model can make predictions of velocity and position

When modeling a cyclist

Image description

Describing the pedaling motion as a step function as show (Describe the step function),

we want to move counterclockwise

And say something about the velocity and position?

Slopes should appear in the velocity gauge, and an increasing function in the position gauge

Image description

Let’s see if we can explore more connections of the model.

Like a direct arrow from Force to Velocity? What does it take to get there? What can we learn?

Image description

This arrow describes a air resistance problem

normally avoided in intro physics class as requires to solve a differential equation.

Image description

However, we are going to tackle it head on because it will give us the ability to solve differential
Equations in haskell

Lets go to the whiteboard

Image description

We are going to re-write newton's second law in terms of a velocity function derivative

Writing the expression in haskell is straightforward.

The sum of the force function depends of velocity at v0, summing all force functions and divide by m.

Image description

The main intuition here is that we will think of newton’s second law as a, wait for it:

first order differential equation generator function ( what a mouth full )
That takes a list of forces (a description of the system)

That is going to be injected to a integral/solver that will

arrive to a solution for velocity

We are going to solve this function using the Euler method

Visually the method takes an initial value calculate the slope using the next value of the function as an approximation

Image description

Obviously, with each step the approximation get worst, but the intuition will prove valuable.

It’s to our advantage to arrive to a solution numerically rather than analytically

The Euler Method will reduce to the solution to:

Velocity at T + delta T equals = initial velocity + derivative of velocity times delta T,

This is what’s called a initial value problem

then we will iterate over this function to get stream of solutions

Image description

Using velocity as a state descriptor of the system

Initial velocity and newton's Second Law as a predictor of that next state,

We can iterate over time to see our predictions evolve

Visually In our model …

Image description

Our model now has a new arrow that takes description of forces to velocity

Lets stimulate again the system with a the same step function and using the cyclist model

Now adding the air resistance to our model

Image description

What can we expect the velocity function look like?

By playing with the area and drag constant

One solution can look like a cyclist reaching terminal speed due to air resistance

Image description

Other is solution expresses velocity when pedaling head wind!!

Image description

Now as you can see this is a pretty cool model:

that solves differential equations

But can we improve it?

Image description

Yes we can:

How about we encode not over real numbers but over vector, and vector spaces.

How would that look like in Haskell?

Image description

Its a data structure that groups 3 values into one.

We enrich the space with the same operations we can do with Real numbers but fitted into Vectors.

For example tilda minus tilda. Takes vector A and Vector B to produce another vector thats a subtracted from b

We have scalar operations

Our last two: we have the dot product which takes two vectors and returns a Real number

And Cross product that takes 2 vectors and returns another Vector.

Image description

Now we want to see if vectors can handle derivatives and antiderivatives as that's how we jump between functions

The difference is barely noticeable in the implementation. And we are caring over the same intuition

Image description

We would like to abstract over all these wires and create a newton solver black box

Image description

The black box that we want to have is

1- given a Description of a system through the sum of Forces
2 - And a initial particle State

3 - return a position function that we can then derive to have a velocity function

We are not going to implement this black box but we are going to explore the types to understand how classical physics works under the hood.

Image description

Image description

Let’s quickly model a constant Force and constant Mass problem in space

The types will show you what’s happening and how the model predicts velocity

We take a numerical method (Euler or RUNGA-KUTTA 2)
Particle state
A delta Particle State

An initial State

We get our a position function

Image description

Rearranging some of the types in the black box, we will explore relativistic and newtonian predictions to the problem

Noticed how the type shows us that we are taking a one Body Force

A DIFFERENTIAL EQUATION, a particle state, a delta Particle state

The intuition that I want to show here that we have modularity in our code.

As we are using the same Differential equation solver for both Body problems.

See how Newton’s model wrongly predicts that velocity will increase without a cap

Newtonian predicts particle will surpass the speed of light

Whereas relativistic has an asymptote at the speed of light

Image description

We just went through 500 years of math and physics in less than 30 minutes, but we were able to take this ride because functional programming is a great way to write math, and math a great tool to handle complexity and describe nature.

I hope this inspires more developers to explore the side of code that is about using math and functions differential equations and math objects, rather blindingly in the next upcoming framework.

Being able to explore nature through Mathematical models using differential equations and making useful predictions though computers is a skill for the future for software engineers.

Thank you!

Top comments (0)