Michael published this video today on the how and why of Gleam’s new try syntax. I thought it would be a good first bit of content to share here on devtalk.
I hope he makes more Gleam educational snippets in future!
Michael published this video today on the how and why of Gleam’s new try syntax. I thought it would be a good first bit of content to share here on devtalk.
I hope he makes more Gleam educational snippets in future!
I reckon Michael should sign up gleam[casts].com! He’s got a good voice and everything was at a relaxed pace which is ideal for screencasts imo (I don’t think he’s signed up yet otherwise I would have @'d him, haha!)
For Gleam
developers which are interested in Elixir
I recommend to check ok library for:
Elegant error/exception handling in Elixir, with result monads.
If for some reason you don’t want to add extra dependencies like that you can always use with/1 special form.
opts = %{width: 10, height: 15}
with {:ok, width} <- Map.fetch(opts, :width),
{:ok, height} <- Map.fetch(opts, :height) do
{:ok, width * height}
end
# returns: {:ok, 150}
opts = %{width: 10}
with {:ok, width} <- Map.fetch(opts, :width),
{:ok, height} <- Map.fetch(opts, :height) do
{:ok, width * height}
end
# returns: :error
Thanks for sharing again! And thanks for the support @AstonJ. I’m glad the video makes a good impression. I’m keen to try to make more and would be happy to cover other parts of Gleam if it would be helpful.
I liked this, and your Elm video too!
One other thing that might confuse people about the try
syntax is what to do if your results
have different error types. If you are looking for ideas for videos, maybe a follow-up about how to use map_error
would be useful too.
Very nice!
I think this is a very clean way to create a helpful feature that is more beginner-friendly than full-blown ‘monadic syntax’.
Of course that does beg the question whether try
will be extended to support e.g. lists, continuations, etc. or whether a different syntax might be introduced there (or whether we stick with the less ‘sugary’ then
/map
-pipelining for those cases).
At the moment the plan is to only have this Result specialisation. Later we may introduce traits, interfaces, or some other form of metaprogramming/ad-hoc polymorphism, at which point we could look at expanding this.