2 ms·
When using `with` and the `{:ok, term} | :error` patterns in Elixir, I just wish we had first class monads. There are some third-party libraries to make workin
by sph 2y ago
When using `with` and the `{:ok, term} | :error` patterns in Elixir, I just wish we had first class monads.
There are some third-party libraries to make working with these a little easier, but it never sat right with me. Probably being so close to the BEAM means we cannot stray very far from what Erlang is doing, but errors would be much nicer to handle with monads.
That said, pattern matching alleviates a lot of pain in many cases. If you have a pipeline of fallible steps, you can do:
def step1({:ok, data}), do: ...
def step1(:error), do: :error
def step2({:ok, data), do: ...
def step2(:error), do: :error
etc.
I think the `with/else` anti-pattern is that your example just feels clunky because of this lack of monads. It is an anti-pattern not because it's a bad idea, but because it is simply unergonomic and just looks bad.
In general, whenever I feel the need to differentiate errors to handle them separately like your example, with a little refactor I can usually simplify the `with` expression and avoid having to do all that ceremony.
- Fire-Dragon-DoL 2y agoGleam has an interesting approach with the USE statement. It looks better than with, but I haven't tried to write code with it yet