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



如何在Scheme中实现assoc和assq?

那么这两个程序的实习生代码是什么呢?

最终,只要它遵守标准中指定的行为,它的实现方式并不重要(请参阅r7rs-small的6.4节(。

在Guile中,看起来assq是这样实现的:

SCM_DEFINE (scm_assq, "assq", 2, 0, 0,
(SCM key, SCM alist),
"@deffnx {Scheme Procedure} assv key alistn"
"@deffnx {Scheme Procedure} assoc key alistn"
"Fetch the entry in @var{alist} that is associated with @var{key}.  Ton"
"decide whether the argument @var{key} matches a particular entry inn"
"@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 equalityn"
"predicate is in use), then return @code{#f}.  These functionsn"
"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)))

最新更新