If it won't be simple, it simply won't be. [Hire me, source code] by Miki Tebeka, CEO, 353Solutions

Thursday, April 09, 2020

Functions as State Machine (Go)

Let's say you'd like to check that a string is a valid floating point (e.g. "3.14", ".2", "-2.718" ...).
One common techinque to solve these kind of problems is to write a state machine.

In our case, the state machine is:

Instead of writng the state machine a one big function with a lot of state and a bunch of "if" statements, we're going to write states as functions.


To simplify things, the end state is going to be nil for easy comparison.
Then our main function will look like:

An here's how startState looks like


When you write this style of code, states are small and contained function. Easier to test and reason about.

Final comments:
  • You can see the full code here
  • This blog was inspired by the Valid Number problem on leetcode
  • Rob Pike has an excellent "Lexcical Scanning in Go" talk that demonstrates this methon

No comments:

Blog Archive