giddie
Guard clause on match operator
I came across this blog post (linked from Elixir Radar) about implementing a match operator that supports guard clauses. And it reminded me that this is a minor annoyance that I come across fairly frequently.
For instance:
# Invalid Syntax
{:ok, x} when is_integer(x) = my_function()
# So I have to do:
{:ok, x} = my_function()
true = is_integer(x)
It seems unlikely that it would just have been overlooked, so I assume there’s some actual reason why the guard syntax isn’t supported. I wonder if anyone knows what it is?
Most Liked
zachallaun
My opinion: the main purpose of guards is to support branching, not to ensure certain invariants. If I see a match clause error, it’s almost always a bug in that code, not a bug in the caller. If I see a function clause error, it’s almost always a bug in the caller. I also feel like invariants should be checked at boundaries, not scattered throughout the code. Guards on match clauses would, I think, encourage a style of programming that is more difficult to understand and harder to debug. My 2c, opinion could change.
giddie
Yeah, this is definitely just a difference in where we’re drawing lines for our definitions. When I think about being defensive in my programming style, I’m including the semantics that we get from OTP. So OTP enables a defensive style by providing automated crash-handling mechanisms on unhappy paths. So the defensiveness is largely “outsourced” to the underlying frameworks when I’m coding.
But the way that manifests is that I’m very explicit about what is the happy path. And actually I think specifying exactly how valid data should look is essential to ensure code fails early and is surfaced in a way that makes it easy to solve.
So all of that to say - I absolutely believe that restricting pattern matches to define a strict happy path is important. And I include all forms of patterns and guards in that definition, which brings me back to - why no guards on match operators?
derek-zhou
I’d rather write:
defp unwrap_integer!({:ok, x}) when is_integer(x), do: x
x = my_function() |> unwrap_integer!()
Instead of asking “why not”, I’d rather ask “how do I write what I want using what is available to me”
Popular in Discussions
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
- #elixirconf-us
- #advent-of-code
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #hex









