silverdr
`with` construct usage question - variables in `else`
I am looking for something like in this simplified example:
with\
%{key: true} <- result = a_function_returning_map()
do
:success
else
_ -> IO.inspect(result)
end
The with construct seems like a good fit for the stream of various actions that may fail and return different results. I can recognise which of them failed based on a specific “fingerprint” of the failure but would like to have full result too. Any suggestions? Or back to nested cases/ifs and Co.?
Most Liked
gregvaughn
It can be done with wrapping tuples, but it’s ugly. You have to do things like:
with {:ok, result} <- get_result(),
{{:ok, other_result}, result} <- {{get_other_result()}, result} do
:success
else
{_, result} -> IO.inspect(result)
end
If you find yourself in that situation, then it’s probably worth stepping back to look at the bigger picture for other design approaches.
But the basic fact is that those bindings available in the expressions and do block are no longer in scope during the else
josevalim
Correct. I generally find having more than one clause in else an anti-pattern. We either use it as a “catch-all”, otherwise I prefer to have each function in with already return the proper types, as shown in your last example.
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #advent-of-code
- #elixirconf-us
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #performance









