42
Railway Oriented Programming
(fsharpforfunandprofit.com)
Welcome to the main community in programming.dev! Feel free to post anything relating to programming here!
Cross posting is strongly encouraged in the instance. If you feel your post or another person's post makes sense in another community cross post into it.
Hope you enjoy the instance!
Rules
Follow the wormhole through a path of communities !webdev@programming.dev
Typically the error track of the railroads analogy is implemented as a short circuit/return, so in effect this behavior IS an early return, but elegantly masked as though you are just handling the happy path.
In rust, if you function returns a Result type (the Either type from the slides), you can track a ? On to the end of any function call that returns a Result. This gets de-sugared to a check for an error and returns from the function early if it is.
At that point, the caller of the function gets to choose if they want to handle the potential failure of your function, or just let it bubble up further by using the ? operator. You end up with the behavior you’re describing, but with the benefit of errors handled by the type system and code that looks cleaner by just (explicitly) handling the happy path.