Understanding the Erlang List, Intersecting Two Lists, and Excluding Values

I need to generate a coordinate set in Erlang. For one coordinate say (x, y) I need to generate (x-1, y-1), (x-1, y), (x-1, y + 1), (x, y-1), (x , y + 1), (x + 1, y-1), (x + 1, y), (x + 1, y + 1). Basically, all surrounding coordinates EXCEPT the middle coordinate (x, y). To generate all nine coordinates, I am doing this currently:

[{X,Y} || X<-lists:seq(X-1,X+1), Y<-lists:seq(Y-1,Y+1)] 

But this generates all the values, including (X, Y). How to exclude (X, Y) from a list using filters in list comprehension?

+7
erlang list-comprehension
source share
3 answers
 [{X,Y} || X <- lists:seq(X0-1,X0+1), Y <- lists:seq(Y0-1,Y0+1), {X,Y} =/= {X0,Y0}]. 
+12
source share

I think the difference between the parameters and the generated values ​​will help a little:

 [{Xc,Yc} || Xc<-lists:seq(X-1,X+1), Yc<-lists:seq(Y-1,Y+1), Xc=/=X orelse Yc=/=Y] 

or more

 [{Xc,Yc} || Xc<-lists:seq(X-1,X+1), Yc<-lists:seq(Y-1,Y+1)] -- [{X,Y}] 
+2
source share

Adding -- [{X,Y}] is likely to be the easiest.

+1
source share

All Articles