簡體   English   中英

字符串作為函數Scheme Racket的參數

[英]Strings as argument to function 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”參數...:[無]

任何人都可以向我解釋我的錯誤是什么,以及通常來說scheme是如何與列表或字符串一起使用的。 我希望有:

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

問題不在於如何將字符串作為參數傳遞,而是...您必須首先了解Scheme的工作方式。 括號放在所有錯誤的位置,有些缺失,某些不必要,並且調用過程的方式不正確。 您的代碼中有很多錯誤,需要完全重寫:

(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

請注意原始實施中的以下錯誤:

  • 您必須將字符串轉換為chars列表,但只有一次才能開始遞歸。
  • 因為我們將需要一個輔助程序,這是一個好主意,使用一個名為let為它-它是一個遞歸過程只是語法糖,不是一個真正的循環
  • 您缺少字符串短於前綴的情況
  • 您不應該display要返回的值,而只返回它們
  • 我們一定不能使用=來比較字符,正確的方法是使用char=? equal? ,這比較籠統
  • cond的最后條件應該是else
  • 最后但並非最不重要的一點是,請記住,在Scheme中,函數的調用方式為: (fx)不是這樣的: f(x) 另外, 除非打算將其作為函數調用, 否則不能將()放在周圍,這就是為什么(str)產生錯誤application: not a procedure; expected a procedure that can be applied to arguments application: not a procedure; expected a procedure that can be applied to arguments

暫無
暫無

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

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