321728 (4) [Avatar] Offline
#1
From the book:

defmodule ListHelper do
  def smallest(list) when length(list) > 0 do
    Enum.min(list)
  end
  def smallest(_), do: {:error, :invalid_argument}
end

You might think that calling ListHelper.smallest/1 with anything other than list will raise an error. This however will not happen. If an error is raised from inside the guard, it will not be propagated, and the guard expression will return false. The corresponding clause will not match, but some other might.
So in the example above, if we call ListHelper.smallest(123), we will get the result :something_else, which demonstrates that an error in the guard expression is internally handled.


However my output from iex...

Interactive Elixir (1.0.2) - press Ctrl+C to exit (type h() ENTER for help)
iex(1)> ListHelper.smallest(123)
{:error, :invalid_argument}
iex(2)>


Did I just misunderstand the passage or was some other error supposed to be returned...?

Thanks.
sjuric (86) [Avatar] Offline
#2
Hi,

This is an error in the text. I have already noticed this myself some time ago, and fixed it. The next MEAP release should contain the correct text.

In any case, the text should read: ... if we call ListHelper.smallest(123), we will get the result {:error, :invalid_argument} ...

The reason for this result is that the first clause doesn't match (since guard expression evaluates to false), so the second clause will match (since it matches everything), and there we explicitly return the error result.
321728 (4) [Avatar] Offline
#3
Cool. Thank you for replying.

Look forward to the next MEAP.
321728 (4) [Avatar] Offline
#4
Edit: Dupe.