2014-11-08 28 views
1

我已經開始研究我的第一個球拍功能,但有一個大問題。球拍簡單的整數生成器函數序列

(define (sequence low hide stride) 
    (letrec ([list-of-int null]) 
      (define (f low hide stride) 
      (if (< low hide) 
       [(begin ((append (list low) list-of-int) 
       (f (+ low stride) hide stride)))] 
       [list-of-int])) 
    (f low hide stride))) 

任何人都可以幫助我理解我的球拍嗎?在我看來,它看起來很好,但不起作用。我在網上找到了更簡單的解決方案:

(define (sequence low high stride) 
    (if (> low high) 
    null 
    (cons low (sequence (+ low stride) high stride)))) 

我明白了,但爲什麼我的代碼不起作用?有誰能夠幫助我?

奧斯卡獎的回答真的很棒)非常感謝親愛的朋友。

回答

5

首先,這個功能已經存在於球拍,它被稱爲range

(range 1 11 1) 
=> '(1 2 3 4 5 6 7 8 9 10) 

現在,關於你實現你要記住方案該列表操作不修改列表就地。特別是,該行不會做你想象一下:

(append (list low) list-of-int) 

果然,append增添了新的元素,但它返回一個新的列表,因爲你沒有把它保存爲一個變量或通過它一個修改失敗的參數。此外,最好使用cons構建輸出列表,使用append將導致二次性能。此外,還有在這裏的錯誤:

[(begin ((

看那些雙[(((呢?他們正在導致報告"application: not a procedure"錯誤。在Scheme中,圍繞()的表達意味着函數應用程序 - 圓括號是而不是用於定義代碼塊,因爲您在其他編程語言中使用{}。一個從無到有的正確實施如下,更接近你腦子裏想的是什麼,並保持相同的行爲range

(define (sequence low high stride) 
    (define (f low cmp acc) ; lower bound, comparator and accumulator 
    (if (cmp high low)  ; exit condition for base case 
     (reverse acc)  ; reverse and return the accumulator 
     (f (+ low stride) ; advance lower bound 
      cmp    ; pass the comparator 
      (cons low acc)))) ; build the list 
    (if (positive? stride)  ; if the step is positive 
     (f low <= '())   ; initialize with <= comparator and '() 
     (f low >= '())))  ; else initialize with >= and '() 

它按預期工作:

(sequence 1 11 1) 
=> '(1 2 3 4 5 6 7 8 9 10) 

(sequence 1 12 2) 
=> '(1 3 5 7 9 11) 

(sequence 10 0 -1) 
=> '(10 9 8 7 6 5 4 3 2 1) 
+1

非常感謝,也有這麼馬赫錯誤一小段代碼。這真的很酷的答案。 – 2014-11-08 13:55:51

+0

看起來像我是一個白癡,但在我的球拍repl它不起作用...我什麼也不懂...... – 2014-11-08 15:32:38

+1

@РоманИванов報告的錯誤是什麼?確保文件的第一行顯示'#lang racket',並且選項中選擇的語言是「從源代碼確定語言」。 – 2014-11-08 15:49:28