2017-01-03 47 views
0

我想獲取兩個字符串作爲參數,並檢查第一個字符串是否是第二個字符串的開始。我不明白,因爲我不知道如何獲取字符串作爲我的函數的參數。字符串作爲函數的參數Scheme Racket

(define starts-with(lambda (prefix str) 
        (define str2 (string->list (str))) 
        (define prefix2 (string->list (prefix))) 
(cond ((= (string-length(prefix2) 0) display "#t") 
     ((= car(prefix2) car(str2)) (starts-with (cdr(prefix2)cdr(str2)))) 
     (display "#f"))))) 

Error: application: not a procedure; expected a procedure that can be 
applied to arguments 

給出:「AB」 參數...:[無]

誰能給我解釋一下什麼是我的錯誤,並在總體方案如何與列表或字符串..?我想有:

(starts-with "baz" "bazinga!") ;; "#t" 

回答

1

的問題不是如何通過字符串作爲參數,問題是......,你必須瞭解方案的工作擺在首位。圓括號在所有錯誤的地方,有些缺失,有些是不必要的,你調用過程的方式是不正確的。有在你的代碼這麼多的錯誤,需要一個完全重寫:

(define (starts-with prefix str) 
    (let loop ((prefix2 (string->list prefix)) ; convert strings to char lists 
      (str2 (string->list str)))  ; but do it only once at start 
    (cond ((null? prefix2) #t) ; if the prefix is empty, we're done 
      ((null? str2) #f) ; if the string is empty, then it's #f 
      ((equal? (car prefix2) (car str2)) ; if the chars are equal 
      (loop (cdr prefix2) (cdr str2))) ; then keep iterating 
      (else #f))))      ; otherwise it's #f 

請注意下面的錯誤在你原來的實現:

  • 您必須將字符串轉換成字符的名單,但在遞歸開始之前只有一次
  • 因爲我們將需要一個輔助程序,它使用一個名爲let它是一個好主意 - 它是一個遞歸過程只是語法糖,不是一個真正的循環
  • 你失蹤時的情形字符串比前綴
  • 你不應該display值,你打算回短,只是返回它們
  • 我們絕不能用於比較字符使用=,正確的方法是使用char=?equal?,這是比較普遍
  • cond的最後一個條件應該是一個else
  • 最後但並非最不重要的是,請記住,在一個函數被稱爲是這樣的:(f x)不是是這樣的:f(x)。此外,你不能把()周圍的東西除非你打算把它調用的函數,這就是爲什麼這樣的:(str)正在產生錯誤application: not a procedure; expected a procedure that can be applied to arguments
+0

洛佩茲第一感謝,第二 - 「prefix2(與字符串>列表前綴)' - 這行只會執行一次,或每個遞歸步驟? – mooly

+1

@mooly在我的代碼中,它只會執行一次;在你的代碼中,它每次都被執行 - 並且會產生一個錯誤,因爲第二次參數已經是一個字符列表,而不是一個字符串。 –