How to simulate logic gates in Elm?

Here is the approach I would take. First, define something like

type alias State = { circuit : List Gate, time : Int }

Here time is discrete. Then rig up a function

nextState : State -> State

This business where you iterate State -> State is a dynamical system – a very general pattern in math, physics and CS. Here is an example of how that works in the Microbial Life app that I refer to below: see line 92

Put a State in your model, initialize it using init, and use update to (a) step forward on time unit at a time on button push, or (b) if the run button is pushed, repeatedly apply nextState. Finally, rig up a view function for State. Given what you have already done in your electric field simulator, you should have no trouble doing that.

I’ve used this approach in various projects, e.g, Microbial Life. I wrote a little article on this on Medium. The code is on GitHub.

I really like your electric field simulation.

PS. It may be that you want to have Rust carry out what amounts to the nextState function, in which case the above is irrelevant. I’d be inclined to try a pure Elm solution first. I’d be very interested to know how that works (and to play with the app). It might be worth benchmarking an Elm solution with 10, 20, 40, etc. gates to see how things scale. I use this package. It is often the case that one can do significant optimizations to improve performance. I wrote a little post on that a while back.

4 Likes