2014-05-12 20 views
-3

我想定義一個列表操作,它以列表和2個函數作爲輸入。讓我更簡潔。這是我將執行的功能。如何將2個參數作爲Scheme中的函數?

這是列表我會用:

(define student-table '(students (name id gpa) (ali 1 3.2) (ayse 2 3.7))) 

,我已經定義了一些功能。

(define (get table row field) 
(nth (list-index field (cadr student-table)) row) 
) 

(define (alter table row fields-values) 
    (cond 
    ((= (length fields-values) 0) row) 
    ((> (length fields-values) 0) 
     (list-with row (list-index (car (car fields-values)) (cadr student-table)) (cadr (car fields-values))) 
     (alter table (list-with row (list-index (car (car fields-values)) (cadr student-table)) (cadr (car fields-values))) (cdr fields-values))))) 

這就是我想實現

(define (update-rows table predicate change)) 

所以,如果我用這個打電話,我希望這個結果的功能。

 
> (update-rows student-table 
    (lambda (table row) 
     (eq? (get table row 'name) 'ali)) 
    (lambda (table row) 
     (alter table row '((gpa 3.3))))) 
=> '(students (name id gpa) (ali 1 3.3) (ayse 2 3.7))) 
+1

那麼,你的問題是什麼? – Chuck

+0

我想定義一個函數,我給它的格式與3個參數。一個是列表,另外兩個是稱爲謂詞和變化的函數。那麼如何用這些函數來定義這個函數呢? – serkanbugur

+0

標題顯示「我如何將2個參數作爲Scheme中的函數?」你想用兩個參數還是三個來定義一個函數?基於你對@ GoZoner的回答的評論,這聽起來像你的問題實際上是沿着「如何編寫一個修改傳入它的列表的函數? –

回答

1

看起來你已經掌握了大部分。填寫update-rows是這樣的:

(define (update-rows table predicate change) 
    ;; Look through all the rows 
    (let looking ((rows (cddr table))) 
    (unless (null? rows) 
     ;; Handle the next row 
     (let ((row (car rows))) 
     (when (predicate table row) 
      (change table row))) 
     ;; Continue looking at the rest 
     (looking (cdr rows)))) 
+0

我理解一般的代碼。但它不會返回任何東西。我如何修改它以返回更改的列表? – serkanbugur

+0

哦,我認爲你的'alter'過程破壞性地修改了表。我想你必須弄清楚上面的代碼是什麼樣的東西,你需要什麼。 – GoZoner

0

我不能檢查,如果這個工程,因爲我沒有list-indexlist-with做。我期望change評估到一個可以替換當前行的元素。

(define (update-rows table predicate change) 
    (cons* (car table) ; keep header 
     (cadr table) ; column symbols 
     ;; process the rest 
     (map (lambda (row) 
       (if (predicate table row) 
        (change table row) 
        row)) 
       (cddr table)))) 

cons*在R6RS中定義。在一些Scheme實現(和Common Lisp)中,它被稱爲list*

相關問題