Erlang Lists: filter / 2 cannot use comma instead of andalso

The following code gives me a warning at compile time: Warning: using the '>' operator has no effect

rd(a,{x,y}), List = [#a{x=1,y=2}, #a{x=3,y=4}], lists:filter( fun(E) -> E#ax > 1, E#ay =:= 2 end, List). 

But when I substitute a comma so there is no warning.

+4
source share
2 answers

Using a comma in this case separates only two actions without affecting each other: E#ax > 1 and the following operation (which is the result of the function) E#ay =:= 2

This means that in your case, the filter function is:

 fun( E ) -> E#ay =:= 2 end 

Only if you write defensive expressions , using a comma is equal to using andalso , otherwise a comma is only a separator between actions.

So, you can rewrite your function in two ways:

1)

 fun (E) when E#ax > 1, E#ay =:= 2 -> true; (_Othervise) -> false end 

2)

  fun( E ) -> (E#ax > 1) andalso (E#ay =:= 2) end 
+7
source

Yes, that's how @stemm said.

In the body , actions are simply separated and gives them order for evaluation. The compiler tells you that since E#ax > 2 has no side effects, it will never throw an exception, and its return value is ignored, and it will never affect execution.

However, in the guard mode , protective tests are detached, which all must succeed for the defense to succeed.

Use caution when viewing guards as normal expressions, which they conduct in different ways, for example, here. Guards also behave differently when they make mistakes. Therefore, when the guards look like expressions, they really are tests.

+1
source

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


All Articles