递归后返回的列表是多余的 [英] Returned list is redundant after recursion

查看:78
本文介绍了递归后返回的列表是多余的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Lisp的新手,在将列表追加到现有列表时遇到问题.

I'm new to Lisp and I have a problem when appending a list to an existing list.

(功能规格)以下函数需要2个args;一个原子和一个列表.该列表采用二维形式,其中每个子列表看起来都像(index counter)(索引和计数器都是原子).如果target等于index es之一,则counter递增.如果没有子列表包含target,请添加一个新的子列表,其中counter = 1.

(Funcion spec) The following function takes 2 args; an atom and a list. The list takes 2-dimensional form where each sub-list looks like (index counter) (both index and counter are atoms). If target is equal to one of the indexes, counter increments. If no sub-list contains target, add a new sub-list with counter = 1.

(defun contained (target list)
  (cond ((null list) (list target 1))
    ((= (car (car list)) target)
     (setf (cadr (car list))
           (+ (cadr (car list)) 1)))
    (t (push (contained target (cdr list)) list))))

问题是target尚不存在.如下所示,列表和括号变得多余了.

The problem is when target doesn't exist yet. As shown below, lists and parentheses get redundant.

> la
((1 4) (2 1))
> (contained 3 la)
(((3 1) (2 1)) (1 4) (2 1))

我想要的是这样的

((3 1) (1 4) (2 1))

对不起,我们无法简化问题,但谢谢.

Sorry not to have been able to simplify the problem, but thanks.

推荐答案

(defun contained (target list)
  (cond
    ((null list) (list target 1)) ; you are returning a new element of target

    ((= (car (car list)) target)
     (setf (cadr (car list))
           (+ (cadr (car list)) 1))) ; you are returning... what?

    ;; yet you are pushing on every recursive call!
    (t (push (contained target (cdr list)) list))))

冒着为您做作业的风险,这是一种做法(在Miron Brezuleanu的帮助下):

At the risk of doing your homework for you, here's one way to do it (with help from Miron Brezuleanu):

(defun contained (target list)
    (let ((elm (assoc target list)))
        (if elm 
            (progn (incf (cadr elm)) list)
            (cons (list target 1) list))))

这是一种使其更接近原始作品的方法

Here's a way to do it closer to your original

(defun contained (target list)
  (cond
    ((null list) (list (list target 1)))
    ((= (car (car list)) target)
     (setf (cadr (car list))
           (+ (cadr (car list)) 1))
     list)
    (t (setf (cdr list) (contained target (cdr list)))
       list)))

这篇关于递归后返回的列表是多余的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆