Using Structs to Represent Chromosomes

Genetic Algorithms in Elixir — by Sean Moriarity (28 / 101)

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Chapter 3 Encoding Problems and Solutions | TOC | Using Behaviours to Model Problems 👉

The chromosomes you created in the previous chapters are enumerable objects that represent solutions to a problem. At the most fundamental level, this is correct; however, in practice, this isn’t a viable implementation.

Consider this: you’re attempting to solve a problem in which the age of the chromosome determines its fitness. One reason you’d do this is to ensure enough variance between generations. Ideally, you’d persist older chromosomes between generations to a certain point, before killing them off once they’ve reached a certain age. In this respect, you ensure an equal distribution of both old and young chromosomes and, thus, naturally occurring variance in the population. Solving a problem like this using only an Enum type to represent a chromosome creates unnecessary complexity. It’s often the case that you need a more robust data structure to keep track of a number of metrics at a time. In Elixir, you can accomplish this task using a struct.

A struct is a map with a few additional features. Structs allow you to define default values and required fields. They also cannot take on additional fields after their creation.

The guarantees that structs provide make them a perfect fit for defining custom types — without the fear of breaking your…

--

--

The Pragmatic Programmers
The Pragmatic Programmers

We create timely, practical books and learning resources on classic and cutting-edge topics to help you practice your craft and accelerate your career.