2016-10-23 21 views
0

添加值的定義列表即時triying做的事情是:在方案

我要創建一個函數,增加值在方案 一本字典,所以我定義的字典作爲列出清單,因爲它遵循:

(define Dictionary '(("key 1" "value 1") ("key 2" "value"))) 

現在對於添加值的函數:

所有我檢查元素不是空的第一和該元素具有鍵和值嘗試之前將其添加到列表中

(define (addElement element mylist) 
    (cond 
     ((null? elemment) 'The_Element_Is_Null) 
     ((null? (cdr element)) 'The_Element_is_singleTon) 
     (#t (cons element mylist)) 
    ) 
) 

並嘗試,因爲它遵循運行:

(addElement '("key 3" "value 3") Dictionary) 

和DrRacket執行它打印以下

(("key 3" "value 3") ("key 1" "value 1") ("key 2" "value")) 

注意,使用利弊的價值,如果它是被顯示的代碼添加到列表中,但值不是,類似於其他語言,可以打印類似的內容

int i = 1; 
print("value = "+ i + 5); 

程序應該打印

value = 6 

,但在現實中變量的值是1,以同樣的方式,我的字典裏沒有得到新的價值觀和執行這個代碼只是打印列表與新的元素,但該元素是不是真的添加到列表

我試過的一個解決方案是使用方法集!嘗試添加的價值,但我得到了相同的結果

(define (addElement element mylist) 
    (cond 
     ((null? elemment) 'The_Element_Is_Null) 
     ((null? (cdr element)) 'The_Element_is_singleTon) 
     (#t (set! myList(cons element mylist))) 
    ) 
) 
+0

你確定這個函數應該修改字典嗎?有一個函數會返回一個新的字典,這個字典就像舊的字典一樣,但添加了這個項目會更加普遍。 (用於像'(定義新詞典(add-element'(「this」「that」))。) – molbdnilo

+0

這正是我需要的 –

回答

0

在流程,大部分列表的操作是「修改」(例如:cons)名單也實際更新的輸入列表,相反,他們會創建一個新列表,並且您應該將其存儲或傳遞給它。

如果您想在程序退出時保留一個程序內的列表修改,您必須明確地修改列表set! - 第二次嘗試的目標是正確的方向,但您只是設置程序的參數,而不是原始列表。我提出了兩種備選方案:

; declare the list outside the procedure 

(define Dictionary '()) 

; 1) either set! the list inside the procedure 

(define (addElement element) 
    (cond 
    ((null? element) 'The_Element_Is_Null) 
    ((null? (cdr element)) 'The_Element_Is_Singleton) 
    (else (set! Dictionary (cons element Dictionary))))) 

(addElement '("key 1" "value 1")) 

; 2) or set! the list with the result of calling the procedure 

(define (addElement element myList) 
    (cond 
    ((null? element) 'The_Element_Is_Null) 
    ((null? (cdr element)) 'The_Element_Is_Singleton) 
    (else (cons element myList)))) 

(set! Dictionary (addElement '("key 1" "value 1") Dictionary)) 

要知道,一般這種風格的過程編程的使用set!嚴重氣餒 - 你想要做的是通過一個過程調用,用於修改列表到另一個程序的結果(函數組合)或相同的過程(作爲遞歸的一部分)並讓它處理新的結果。請記住,Scheme是核心的一種函數式編程語言,事情的執行方式與您習慣的不同。

+0

@ D.Shinoda這是否回答了您的問題?如果是這樣,請不要忘記[接受](https:// meta。stackexchange.com/questions/5234/how-does-accepting-an-answer-work)它,只需點擊左邊的複選標記;) –

+0

嘿,剛剛發現了一種不同的方式,消除了設置的需要!使用(define())重新定義我的函數的輸出列表是什麼assigment是關於,但無論如何 –