I was trying to get further involved but now you pinged me, d’oh
I never said “should.” OP asked why things are the way they are and I was trying to provide an answer. People are free to write code how they want. Also, OP is asking why we can’t do guards in inline matches. You example uses case
.
In short, @zachallaun said what I meant but far more eloquently. By “not meant for type assertions” I meant that they are “meant” for flow control. And I don’t buy that they are 100% same thing, though of course they are very closely related. For example in LiveView, José recommends (not a “commands”) matching only against keys that will satisfy a match:
def handle_event("foo", %{"id" => id}, socket) do
current_user = socket.assigns.current_user
as opposed to something like:
def handle_event("foo", %{"id" => id}, %{assigns: %{user: user}} = socket) do
It’s already been touched on but your definition of defensive programming is not the “regular” one and it’s certainly not Erlang’s definition. Generally when we do inline matches it’s on stuff that can fail either because it’s a side effect or the result of parsing user input:
:ok = network_request()
{:ok, result} = parse_user_input_i_wont_deal_with_if_its_wrong_for_some_reason("hi!")
You otherwise don’t usually see random type assertions in a function body. I’m actually having a hard time picturing when this would even be useful—why wouldn’t you check it in the function head? In any event, if you have a use-case that’s fine but again I was just trying to answer the question. There is a direct example of how this is not intended in the link above but program however you want.
This is sort of missing the point—if you’ve checked at the boundaries and you’re getting a nil
error, your boundary-checking is wrong. The whole point of boundary casting is to get data into a a solid, known shape (ideally a struct AFAIC though whole other convo).

I’d go so far as to say that guards semantically are pattern matches. They offer programmable extension to patterns.
Agreed. The docs even touch on this.