# distance

The `distance` filter is a numeric filter that takes two position filters enclosed in parentheses as arguments. It returns the number of moves in the game tree that separate the positions represented by these arguments:

`  distance(x y)`

The value `distance(x y)` can be computed as follows:

• If either the filter `x` or the filter `y` does not match the position, then neither does the `distance` filter
• otherwise, let L be the LCA of `x` and `y`. Then the value is the sum of `distance(x L)` and `distance(y L)`

Note that:

• if `x==y` then `distance(x y)==0`
• if `x` is an ancestor of `y` then their distance is the number of moves between them.

In CQL, this could be written as a function:

```   function(x y){
L= LCA(x y)
(x:ply - L:ply) + (y:ply  - L:ply)}```

This works because `x:ply` is the value of the `ply` filter at the position `x`, which is the same as saying the ply value of position `x`.

Don't confuse `distance` with the Euclidean distance between two squares on the chessboard. The concepts aren't related.

# Examples

The `distance` filter is mainly used in echo filters , which looks for pairs of positions that have certain similarities. Often we want to make sure the positions are not "too close" in the game tree, when the resulting patterns is boring. Sometimes we want to sort by this distance as well, since how far apart they are.

`distance` is used in with the `echo` filters in fatamorgana.cql, queenpawnpinecho.cql, and underpromotionecho.cql in this way.