[英]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
請注意原始實施中的以下錯誤:
let
為它-它是一個遞歸過程只是語法糖,不是一個真正的循環 display
要返回的值,而只返回它們 =
來比較字符,正確的方法是使用char=?
或equal?
,這比較籠統 cond
的最后條件應該是else
(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.