所以,id喜欢接受一个数字列表,将其原子化(删除嵌套整数),然后找到最大值。我编写了两个单独完成此功能的函数,但无法弄清楚如何在LISP中将它们组合在一起,这样我就可以进行一次调用并让它们都运行。任何帮助,将不胜感激。
:Atomize function to remove nests
:(atomify ‘( a (b c) (e (f (g h) i)) j)->(a b c e f g h i j)
(defun atomify (numbers)
(cond ((null numbers) nil)
((atom (car numbers))
(cons (car numbers)
(atomify (cdr numbers))))
(t
(append (atomify (car numbers))
(atomify (cdr numbers))))))
:Max value of a list of integers function
(defun large_atom (numbers)
(if (null numbers)
0
(max (first numbers)
(large_atom (rest numbers)))))
答案 0 :(得分:2)
杰米。你的方式有两个步骤: 1.拼合列表 2.从第1步的结果中找出最大值 在这种情况下,这是真正的方式。但是你需要通过一个函数调用来完成它。这很简单。只需使用apply,max,当然还有{{3}}
# Picking random word to guess
word = ['open', 'real', 'hang', 'mice'].sample
loop do
puts "So, guess the word:"
input_word = gets.strip
if word == input_word
puts("You are right, the word is: #{input_word}")
break
end
puts "You typed: #{input_word}"
# Split both the word to guess and the suggested word into array of letters
word_in_letters = word.split('')
input_in_letters = input_word.split('')
result = []
# Iterate over each letter in the word to guess
word_in_letters.each_with_index do |letter, index|
# Pick the corresponding letter in the entered word
letter_from_input = input_in_letters[index]
if letter == letter_from_input
result << "#{letter_from_input} - Correct"
next
end
# Take nearby letters by nearby indexes
# `reject` is here to skip negative indexes
# ie: letter 'i' in a word "mice"
# this will return 'm' and 'c'
# ie: letter 'm' in a word "mice"
# this will return 'i'
letters_around =
[index - 1, index + 1]
.reject { |i| i < 0 }
.map { |i| word_in_letters[i] }
if letters_around.include?(letter_from_input)
result << "#{letter_from_input} - Close"
next
end
result << "#{letter_from_input} - Incorrect"
end
puts result.join("\n")
end
另一种方式,就是不要压平源列表。但在这种情况下,您需要找到第一个值来与其他值进行比较。亲自尝试一下。
答案 1 :(得分:2)
这是另一种解决问题的方法:不是扁平化列表,而是递归地向下移动。这非常清楚列表的结构必须是什么:一个好的列表是一个非空的正确列表,每个列表的元素都是整数或良好的列表。
这种方法的问题在于它不是尾递归的,因此它必然会在非常大的结构上失败(即使它是尾递归的,CL也不承诺处理尾递归。
(defun greatest-integer (good-list)
;; a good list is one of:
;; - a cons of a good list and either a good list or ()
;; - a cons of an integer and either a good list or ()
;; In particular it can't be () and it can't be an improper list
;;
(destructuring-bind (a . b) good-list
;; a can be an integer or a good list, b can be null or a good list
(etypecase b
(null
(etypecase a
(integer a)
(cons (greatest-integer a))))
(cons
(max (etypecase a
(integer a)
(cons (greatest-integer a)))
(greatest-integer b))))))