1

これは Common Lisp コードです:

(defun take (L)
  (if (null L) nil
     (cons (car L) (skip (cdr L)))))

(defun skip (L)
  (if (null L) nil
     (cons (car L) (take (cdr L)))))

ここでの考え方は、「take」は入力リストのすべての奇数シーケンス要素を提供し、「skip」は入力リストのすべての偶数シーケンス要素を提供するというものです。ただし、どちらの場合もリスト全体が返されます。

このコードのエラーは何ですか? SML の同様のコードで目的の出力が得られるため、これは CL がリストを処理する方法と関係があります。

fun take(lst) = 
     if lst = nil then nil 
     else hd(lst)::skip(tl(lst))
and
    skip(lst) = 
     if lst = nil then nil 
     else hd(lst)::take(tl(lst));
4

3 に答える 3

3

takeskipは同一であるため、謎ではありません。-ingskipの代わりに末尾呼び出しを行う必要があります。consここで返されるのは consing です。

于 2013-11-23T01:11:03.657 に答える
2

It's worth pointing out that indexing in Common Lisp (like many other programming languages) starts with 0, so the even-indexed elements of a list are the first, the third, the fifth, and so on, since those have indices 0, 2, 4, etc. It's also worth noting that in Common Lisp, you can take the rest of the empty list and get back the empty list. (You can't do this in every Lisp, though. E.g., in Scheme it's an error to call cdr on something that's not a pair.) This means that you can implement even-elements and odd-elements rather easily. even-elementsjust returns a list of the first element, and the odd elements of the rest of the list. odd-elements returns the even-elements of the rest of the list:

(defun even-elements (list)
  (if (endp list) list
      (list* (first list) (odd-elements (rest list)))))

(defun odd-elements (list)
  (even-elements (rest list)))

These behave in the expected fashion:

CL-USER> (even-elements '(0 1 2 3 4 5))
(0 2 4)
CL-USER> (odd-elements '(0 1 2 3 4 5))
(1 3 5)

Of course, if you note that the call to (odd-elements x) is just a call to (even-elements (rest x)), we could have implemented even-elements as follows, and had the same result:

(defun even-elements (list)
  (if (endp list) list
      (list* (first list) (even-elements (rest (rest list))))))
于 2013-11-24T04:11:14.753 に答える