Next: , Previous: , Up: iklib records defs   [Index]


6.19.1.6 The custom equality predicate

In a use of the syntax define-record-type, the definition clause:

(equality-predicate ?expr)

allows the specification of an expression ?expr which must evaluate to a custom equality–predicate protocol–function for instances of the record–type; iklib records equality, for the API that manipulates record’s equality predicates.

If the record–type has a parent: the protocol function is applied to the equality predicate of the parent (or #f if the parent has no equality predicate) and the resulting value must be a function, which becomes the equality predicate of the record–type.

If the record–type has no parent: the protocol function is called as a thunk and the resulting value must be a function, which becomes the equality predicate of the record–type.

The equality predicate is used when comparing records of the same record–type with equal?, but not with eqv?.

In the following example, we define a custom equality predicate that just compares all the fields; the only difference between the default equality predicate record=? and this implementation, is that this one compares the fields using = rather than equal?:

(define-record-type <duo>
  (fields one two)
  (equality-predicate
    (lambda ()
      (lambda (A B)
        (and (= (<duo>-one A)
                (<duo>-one B))
             (= (<duo>-two A)
                (<duo>-two B)))))))

(equal? (make-<duo> 1 2) (make-<duo> 1 2))      ⇒ #t
(equal? (make-<duo> 1 2) (make-<duo> 1 99))     ⇒ #f

In the following example, we define a custom equality predicate that compares only some of the fields:

(define-record-type <duo>
  (fields one two)
  (equality-predicate
    (lambda ()
      (lambda (A B)
        (= (<duo>-one A)
           (<duo>-one B))))))

(equal? (make-<duo> 1 2) (make-<duo> 1 99))     ⇒ #t
(equal? (make-<duo> 1 2) (make-<duo> 99 2))     ⇒ #f

this kind of equality predicate is especially useful, for example, when some fields are used to memoise values.


Next: , Previous: , Up: iklib records defs   [Index]