Hacker Newsnew | past | comments | ask | show | jobs | submitlogin
Functional State Machines in Rust: Typestate and Newtype Patterns (acm.org)
54 points by matt_d 7 hours ago | hide | past | favorite | 11 comments
 help



Types are puzzles. A good Rustacean will make sure that the pieces fit to make the picture.

That's why in crates where I need to make sure certain functions are called in order, I use a Ticket<T>, where one function returns a Ticket<Func1Done> with the output and the other has to consume it as an input.

The typestate pattern is a specialization of making only valid states representable


One of my favorite useful patterns

why not just create a wrapper type for the payload that is returned by func1 and func2 takes it as a parameter?

That's fair but then you have to make your args a struct for this bespoke purpose; an anti pattern.

Also, many other functions can depend on the ticket from func_1. So making the ticket separate and generic on the process is the right (imo) solution here.


Because you may want to share certain behaviors between the two wrapper types via generic impl

That sounds like a Wrapper<Func1Payload>, not a Ticket<Func1Call> that will become an extra parameter of Func2 whose only purpose is to prove to Func2 that you called Func1.

Maybe I misunderstood something.


I use Typestates and Newtypes extensively. The metric that shows Typestate and Newtypes are beneficial is: How many method calls or parameters can be called / used that compile but are not valid use cases. You want to minimise this number. I love having a type state where I can only make 1 or 2 method calls because the state enforces there are only a few parsing / validation / transition methods available. And there is only one valid way to supply the parameters, I cannot use the strings in the wrong location. I only wish we had named parameters like ObjC.

This was a talk at the FUNARCH workshop at this year’s ICFP.

Here’s the livestream: https://www.youtube.com/live/c0pw1iVs_Q0?is=hwm2xa4cZOcqF5tW

Well post the individual talks in the following days!



Could someone compare this to ST in Idris?

Yes, I believe it should be possible for someone to do that.



Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: