簡體   English   中英

清單的方案和

[英]Scheme sum of list

首先,這是家庭作業,但是我只是在尋找有關如何執行此操作的提示或偽代碼。

我需要使用recursion匯總列表中的所有項目。 但是,如果遇到列表中的非數字內容,則需要返回空集。 這是我的嘗試:

(DEFINE sum-list
  (LAMBDA (lst)
    (IF (OR (NULL? lst) (NOT (NUMBER? (CAR lst))))
      '()
      (+
        (CAR lst)
        (sum-list (CDR lst))
      )
    )
  )
)

之所以失敗,是因為它無法將空集添加到其他內容。 通常,如果它不是數字,我只會返回0並繼續處理列表。

我建議您使用並返回一個累加器來存儲和; 如果在遍歷列表時發現非數字,則可以立即返回空列表 ,否則遞歸將繼續進行,直到列表用盡。

這些內容(填空!):

(define sum-list
  (lambda (lst acc)
    (cond ((null? lst) ???)
          ((not (number? (car lst))) ???)
          (else (sum-list (cdr lst) ???)))))

(sum-list '(1 2 3 4 5) 0)
> 15

(sum-list '(1 2 x 4 5) 0)
> ()

我會為此:

(define (mysum lst)
  (let loop ((lst lst) (accum 0))
    (cond
      ((empty? lst) accum)
      ((not (number? (car lst))) '())
      (else (loop (cdr lst) (+ accum (car lst)))))))

您的問題是您需要使用cond,而不是如果需要-需要考慮三個可能的分支。 第一個是遇到一個非數字,第二個是遇到列表的末尾,第三個是需要遞歸到列表的下一個元素。 第一個問題是您要組合非數字大小寫和空列表大小寫,這需要返回不同的值。 遞歸的情況在大多數情況下是正確的,但是您必須檢查返回值,因為遞歸調用可以返回一個空列表。

因為我不夠聰明,無法在一個函數中弄清楚如何做到這一點,所以讓我們痛苦地講清楚:

#lang racket

; This checks the entire list for numericness
(define is-numeric-list?
  (lambda (lst)
    (cond
      ((null? lst) true)
      ((not (number? (car lst))) false)
      (else (is-numeric-list? (cdr lst))))))

; This naively sums the list, and will fail if there are problems
(define sum-list-naive
  (lambda (lst)
    (cond
      ((null? lst) 0)
      (else (+ (car lst) (sum-list-naive (cdr lst)))))))

; This is a smarter sum-list that first checks numericness, and then
; calls the naive version.  Note that this is inefficient, because the
; entire list is traversed twice: once for the check, and a second time
; for the sum.  Oscar's accumulator version is better!
(define sum-list
  (lambda (lst)
    (cond
      ((is-numeric-list? lst) (sum-list-naive lst))
      (else '()))))

(is-numeric-list? '(1 2 3 4 5))
(is-numeric-list? '(1 2 x 4 5))

(sum-list '(1 2 3 4 5))
(sum-list '(1 2 x 4 5))

輸出:

Welcome to DrRacket, version 5.2 [3m].
Language: racket; memory limit: 128 MB.
#t
#f
15
'()
> 

我懷疑您的作業期望更多的學術性

嘗試制作一個“ is-any-nonnumeric”函數(使用遞歸); 那么您就只是(或(是任何數字列表)(和列表))傻瓜。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM