You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Common Lisp中add-movie函数无法正常工作的技术求助

问题分析与修复

你的add-movie函数存在语法错误和逻辑错误,导致无法正常运行,下面逐一说明并修复:

1. 语法错误:dotimes使用格式错误

dotimes的标准语法是(dotimes (变量 次数) 代码块),原代码里dotimes i (length array)缺少包裹变量和次数的括号,这会直接引发语法报错,正确写法应为(dotimes (i (length array)) ...)。

2. 逻辑错误:遍历与插入逻辑混乱

原代码逻辑完全不符合需求:

  • 遇到非nil元素时,只要标题不重复就直接替换该位置的元素,会覆盖已有电影数据
  • 未完整遍历数组检查所有元素是否存在重复,也未判断数组是否已满

修复后的代码

(defstruct movie
  title director year type)

(defun add-movie (movie array)
  (let ((mtitle (movie-title movie)))
    ;; 第一步:遍历数组检查是否存在重复标题
    (dotimes (i (length array))
      (let ((current (aref array i)))
        (when (and current (equal (movie-title current) mtitle))
          ;; 找到重复,返回nil表示添加失败
          (return-from add-movie nil))))
    ;; 第二步:遍历数组找第一个空位置插入
    (dotimes (i (length array))
      (when (null (aref array i))
        (setf (aref array i) movie)
        ;; 插入成功,返回t表示成功
        (return-from add-movie t)))
    ;; 数组已满,返回nil表示添加失败
    nil))

测试验证

CL-USER> (defvar a (make-array 4 :initial-element NIL))
A
CL-USER> (add-movie (make-movie :title "Titanic" :director "James Cameron" :year 1997 :type "Romance") a)
T
CL-USER> a
#(#S(MOVIE :TITLE "Titanic" :DIRECTOR "James Cameron" :YEAR 1997 :TYPE "Romance") NIL NIL NIL)
CL-USER> ;; 尝试添加重复标题的电影
CL-USER> (add-movie (make-movie :title "Titanic" :director "Someone" :year 2024 :type "Drama") a)
NIL
CL-USER> ;; 填满数组后尝试添加新电影
CL-USER> (add-movie (make-movie :title "Avatar" :director "James Cameron" :year 2009 :type "Sci-Fi") a)
T
CL-USER> (add-movie (make-movie :title "Inception" :director "Christopher Nolan" :year 2010 :type "Sci-Fi") a)
T
CL-USER> (add-movie (make-movie :title "Interstellar" :director "Christopher Nolan" :year 2014 :type "Sci-Fi") a)
T
CL-USER> (add-movie (make-movie :title "Dune" :director "Denis Villeneuve" :year 2021 :type "Sci-Fi") a)
NIL
CL-USER> a
#(#S(MOVIE :TITLE "Titanic" :DIRECTOR "James Cameron" :YEAR 1997 :TYPE "Romance")
  #S(MOVIE :TITLE "Avatar" :DIRECTOR "James Cameron" :YEAR 2009 :TYPE "Sci-Fi")
  #S(MOVIE :TITLE "Inception" :DIRECTOR "Christopher Nolan" :YEAR 2010 :TYPE "Sci-Fi")
  #S(MOVIE :TITLE "Interstellar" :DIRECTOR "Christopher Nolan" :YEAR 2014 :TYPE "Sci-Fi"))

内容的提问来源于stack exchange,提问作者A K

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 08:17:31