Scheme中assoc和assq是如何实现的?

How are assoc and assq implemented in Scheme?

assoc和assq在Scheme中是如何实现的?

那么这两个程序的实习代码是多少?

最终,只要它符合标准中指定的行为(请参阅 r7rs small 的第 6.4 节),如何实施并不重要。

Guile, it looks like assq is implemented like this中:

SCM_DEFINE (scm_assq, "assq", 2, 0, 0,
           (SCM key, SCM alist),
        "@deffnx {Scheme Procedure} assv key alist\n"
        "@deffnx {Scheme Procedure} assoc key alist\n"
        "Fetch the entry in @var{alist} that is associated with @var{key}.  To\n"
        "decide whether the argument @var{key} matches a particular entry in\n"
        "@var{alist}, @code{assq} compares keys with @code{eq?}, @code{assv}\n"
        "uses @code{eqv?} and @code{assoc} uses @code{equal?}.  If @var{key}\n"
        "cannot be found in @var{alist} (according to whichever equality\n"
        "predicate is in use), then return @code{#f}.  These functions\n"
        "return the entire alist entry found (i.e. both the key and the value).")
#define FUNC_NAME s_scm_assq
{
  SCM ls = alist;
  for(; scm_is_pair (ls); ls = SCM_CDR (ls)) 
    {
      SCM tmp = SCM_CAR (ls);
      SCM_ASSERT_TYPE (scm_is_pair (tmp), alist, SCM_ARG2, FUNC_NAME,
               "association list");
      if (scm_is_eq (SCM_CAR (tmp), key))
    return tmp;
    }
  SCM_ASSERT_TYPE (SCM_NULL_OR_NIL_P (ls), alist, SCM_ARG2, FUNC_NAME,
           "association list");
  return SCM_BOOL_F;
}
#undef FUNC_NAME

哪个是 C 等效项(不包括某些类型检查):

(define (assq key alist)
  (let loop ((ls alist))
    (if (pair? ls)
      (let ((tmp (car ls)))
        (if (eq? (car tmp) key)
          tmp
          (loop (cdr ls))))
      #f)))