-3

セットからすべての奇数を追加する関数を clisp で作成する必要があります。たとえば、サブセット (2,8) の場合、結果は 15(3+5+7) になります。何か提案はありますか? 私はこのようなものを持っています。ここで、a はセットの始まりであり、b は終わりです。

(defun add (a b)
(if(and(< a x) (> b x))
    (if(even(x))
        ((setq ( x (+a 1))) (+ x 2))
        ((setq(x a)) (+ x 2))
            )))

編集:

(defun add (a b)
(if(and(< a x) (> b x))
    (if(evenp x))
        ((setq ( x (+a 1))
            (loop for x from a to b do (+ x 2))))
        ((setq(x a)) (+ x 2)
            (loop for x from a to b do (+ x 2)))
                ))
4

4 に答える 4

1

I was going to do my usual shtick and put on the code-review hat, but having properly formatted your second attempt, there are too many problems here to take an incremental approach. You need to sit down and explain what you intended this code to do.

Specifically, what's going on with x? Is that meant to be a global binding that you're re-setting each time, or did you mean to define a local binding and accidentally forgot that both the ifs need the variable before you get around to it? What are you trying to do with those setqs, and what are you trying to do with those loops (as written, neither do anything)?


[temporarily dons code-review hat]

First up, kindly format your code properly. It's a small thing, but it increases readability by quite a bit.

(defun add (a b)
  (if (and (< a x) (> b x))
     (if (evenp x))
     ((setq (x (+ a 1))
            (loop for x from a to b do (+ x 2))))
     ((setq (x a)) (+ x 2)
      (loop for x from a to b do (+ x 2)))))

And with the proper indentation level, quite a few errors just fall out at you right away.

  • First off, that top if has three clauses in it (the if and two setqs for some reason).
  • Second, that second if has no clauses, just a test. Which means it does nothing
  • Third, you're calling some very oddly named functions in the if body. I'm willing to guarantee that ((setq (x a)) (+ x 2) (loop for x from a to b do (+ x 2))) isn't what you mean, because that's calling the function (setq (x a)) on the arguments (+ x 2) and (loop ...).
  • Fourth, you invoke setq in two different incorrect ways. (setq (x (+ a 1)) this is attempting to set the result of calling the function x on (+ a 1) to NIL. (setq (x a)) (+ x 2) this is trying to set the result of calling the function x on a to NIL, then evaluating and discarding (+ x 2).
于 2013-05-07T13:19:12.150 に答える
0

構文の問題を修正するまで、アルゴリズムの問​​題に直面することはありません。あなたは解決策を推測しているようですが、まだ推測をまとめていません。コードはコンパイルされず、実行されません。あなたが Lisp に似た言語を勉強しているのは、まさに些細な探索ができるからです。だから探検してください。

(defun add (a b)
  (cond ((evenp a) (add (+ a 1) b))
        ((> a b)   0)
        (t         (+ a (add (+ a 2) b)))))
于 2013-05-07T14:15:57.993 に答える