Hacker News new | past | comments | ask | show | jobs | submit login

> returns early with the thing that didn't match

What if the things are all of a different type? This is dynamically typed? You have to look at the type of the thing to find out where it went wrong, and guess which failing expression it came from?

It's like halfway to reinventing exception handling.

  with pat1 expr1, pat2, expr2 .... 
  do
     happy case // all matched
  catch   // various unhappy patterns matched against mismatching expr
     pat1 do ... end
     pat2 do ... end
     ...
  end
Just call it "else" or something instead of "catch" and then it doesn't look like exception handling.



Well, this isn't the only way to do things. There are exceptions in elixir and you can catch them if you want. But most functions that can fail have two versions

File.read() returns {:OK, contents} or {:error, reason}

So you can pattern match on the result.

File.read!() returns contents or raises an exception.

The first one allows you to use errors as values and handle the problem at the source. The latter assumes its going to be successful and either makes you catch the exception or, more likely for elixir, let the process crash.

The with statement is a good fit for certain domains where otherwise you might have a bunch of nested cases.

If you are worried about it returning a different type you can wrap it in the else block

    with {:ok, bar} <- func(foo)
    do
        bar
    else
        value -> {:failed, value}
end

So you can make your failed cases more homogeneous to pattern match on. You can even pattern match on the different failed cases if you want to ensure more homogeneity.

If using with doesn't make sense for the domain there are other constructs in the language that will




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: