我最近开始学习lisp.像许多其他人一样,我正在努力解决Project Euler问题,但是我对问题14:最长的Collatz序列有点困惑.
这是我到目前为止:
(defun collatz (x)
(if (evenp x)
(/ x 2)
(+ (* x 3) 1)))
(defun collatz-sequence (x)
(let ((count 1))
(loop
(setq x (collatz x))
(incf count)
(when (= x 1)
(return count)))))
(defun result ()
(loop for i from 1 to 1000000 maximize (collatz-sequence i)))
Run Code Online (Sandbox Code Playgroud)
这将正确打印最长序列(525),但不能生成产生最长序列的数字.
我想要的是
result = maximum [ (collatz-sequence n, n) | n <- [1..999999]]
Run Code Online (Sandbox Code Playgroud)
如果可能的话,翻译成Common Lisp.
我试图通过另一个结构实例或其名称访问结构实例的字段.因为这听起来非常令人困惑,我有一个(非常构造的)例子:
(defstruct author
(name nil)
(books '())
(years '()))
(defstruct book
(name nil)
(author '())
(copy-sold '()))
(defparameter hitchikers-guide
(make-book :name "Hitchikers-Guide"
:author '(douglas-adams)
:copy-sold '(a lot)))
(defparameter douglas-adams
(make-author :name "Douglas Adams"
:books '(Hitchikers-guide restaurant life-and-universe fish)
:years '(too few)))
(defparameter authors
'(douglas-adams pterry))
Run Code Online (Sandbox Code Playgroud)
我有实例hitchikers-guide.如果我想查找其作者的所有书籍,我可以输入REPL (author-books douglas-adams),我会得到他所有书籍的清单.但是,如果我进入
(author-books (first (book-author hitchikers-guide)))
要么
(author-books (first authors))
我收到错误消息:
值DOUGLAS-ADAMS不是预期类型AUTHOR.
我做错了,还是没办法以这种方式访问这些字段?