# How to simulate logic gates in Elm?

**URL:** <https://discourse.elm-lang.org/t/how-to-simulate-logic-gates-in-elm/5462>\
**Category:** Learn\
**Created:** [April 7, 2020, 11:57am UTC](https://discourse.elm-lang.org/t/how-to-simulate-logic-gates-in-elm/5462 "2020-04-07T11:57:23Z")\
**Posts on this page:** 1\
**Showing post:** 4

<div class="post-metadata">

**Author:** ![jxxcarlson](https://yyz1.discourse-cdn.com/flex035/user_avatar/discourse.elm-lang.org/jxxcarlson/32/866_2.png) [@jxxcarlson](https://discourse.elm-lang.org/u/jxxcarlson)\
**Post date:** [April 8, 2020, 10:49am UTC](https://discourse.elm-lang.org/t/how-to-simulate-logic-gates-in-elm/5462/4 "2020-04-08T10:49:23Z")

</div>

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

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

```

Here `time` is discrete. Then rig up a function

```auto
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](https://github.com/jxxcarlson/elm-microbialLife/blob/master/src/Main.elm#L78-L102)

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](https://jxxcarlson.github.io/app/microbial-life/index.html). I wrote a little article on this on [Medium](https://medium.com/@jxxcarlson/microbial-i-b1610ca23884). The code is on [GitHub](https://github.com/jxxcarlson/elm-microbialLife).

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](https://package.elm-lang.org/packages/elm-explorations/benchmark/latest/). It is often the case that one can do significant optimizations to improve performance. I wrote [a little post](https://discourse.elm-lang.org/t/performance-optimization/5105) on that a while back.

---

_[View the full topic](https://discourse.elm-lang.org/t/how-to-simulate-logic-gates-in-elm/5462)._
