This is a nice example of an intermediate to somewhat advanced application of DCGs.