Erlang guard expressions: using "and" vs using "comma"

I just started learning Erlang, but I can’t understand why this code does not match the function call test: sum (3)

-module(test). -export([sum/1]). sum(0) -> 0; sum(N) when is_integer(N) and N>0 -> N + sum(N - 1). 

... while it does:

 -module(test). -export([sum/1]). sum(0) -> 0; sum(N) when is_integer(N), N>0 -> N + sum(N - 1). 

Am I missing something about two different approaches?

+5
source share
1 answer

This is due to the priority of the operator.

As defined in reference , the and operator precedes > , so what you actually get in your first code snippet:

 sum(N) when (is_integer(N) and N)>0 -> N + sum(N - 1). 

So, in your case, you are comparing (true and 3) > 0 , which cannot be true, so your guard will never match.

To fix this, you can write your guard as follows:

 sum(N) when (is_integer(N)) and (N>0) -> N + sum(N - 1). 

PS Brackets for is_integer/1 not needed in this scenario, but it may look clearer.

+6
source

Source: https://habr.com/ru/post/1232403/


All Articles