返回一个元素,然后从 Scheme 中的列表中删除该元素

Returning an element and then deleting the element from a list in Scheme

我在 Scheme 中有一个包含数字的列表。我编写了一个函数,将一个数字和一个对象列表作为输入,并检查对象的置信度值是否与该数字匹配。

一旦获得置信度值与给定数字匹配的对象,我想在返回对象后从列表中删除该对象。我该怎么做呢?到目前为止,这是我的代码:

(define (get-wordpair mi wordpairs)
    (define current-wp (car wordpairs))
    (define confidence (tv-conf (cog-tv current-wp)))
    (if (equal? confidence mi)
        current-wp
        (get-wordpair mi (cdr wordpairs))))

使用filter从列表中删除置信度值与给定数字匹配的对象:

(filter (lambda (e)
          (not (equal? (tv-conf (cog-tv e)) mi)))
        wordpairs)

相反,此表达式将 return 包含那些 具有预期置信度的对象的列表(可能不止一个!)

(filter (lambda (e)
          (equal? (tv-conf (cog-tv e)) mi))
        wordpairs)

因此,调用 both 表达式来获取包含所需对象的两个列表,如果可以对输入列表执行两次传递。要获得执行单次传递的更有效的解决方案,请检查您的解释器的文档以查看它是否提供 partition procedure, or use SRFI-1:

(let-values (((with-confidence no-confidence)
              (partition (lambda (e)
                           (equal? (tv-conf (cog-tv e)) mi))
                         wordpairs)))
  ; do something with the list of objects that have the
  ; required confidence (with-confidence) and the list of
  ; those which don't have the confidence (no-confidence)
  )