[英]Using recursion to getNth position for Racket
我必須在Racket中編寫一個遞歸調用,使我們能夠獲得給定列表的第N個位置。 例如(getNth 3'(1 2 3 4))應該返回4,如果列表為空或位置不存在,則返回為空列表。
這是我的代碼:
(define getNth
(lambda (ls)
(if (= ls null?) 1
(getNth ls(append '(car ls)(cdr ls))))))
得到這個錯誤:getnth:arity不匹配; 預期的參數數量與預期的給定數量不匹配:1個給定的:2個參數...:4()
如果您需要遞歸語句,則為:
如果LS = null,則返回基數-getNth N LS)=()
如果N> = 1,則遞歸調用-(getNth N LS)=(getNth N(追加'(car LS)(cdr LS)))
即時通訊陷入困境,我不知道如何實現這一目標。
假設您的getNth可以從列表中取消“ N”(而不是固定的N即get3rd),則您確實缺少一個參數:
(define getNth
(lambda (n list)
(cond ((null? list) '())
((= n 0) (car list))
(else (getNth (- n 1) (cdr list))))))
這基本上是直到我得到想要的數字,然后遞減它並“彈出”第一個元素,直到列表的第一個元素是我想要的那個元素,即列表的其余部分。
您的lambda僅采用您定義它的方式的一個參數,而這正是您收到的錯誤消息;)
我想我適當地平衡了括號:)
遞歸技巧:它的通用概念很簡單:
重新提醒是“如果發生了終止條件,我就完成了,返回適當的值。否則,將參數增加到終止條件並用這些新參數調用自己”
當終止條件可以有異常時,它將變得很復雜。 因為如果您不能簡單地將其表示為“如果執行此操作,否則將以增量重做”,則可能會出錯...
您的代碼有幾個問題。
ls
。 ls
為空列表時,結果為1
'(car lst)
之間'(car lst)
,該值的值是列表(car lst)
和(cdr ls)
(列表ls
除第一對外) (define get-nth
(lambda (index lst)
(if (= index 0) ; when index is zero
(car lst) ; return the first element
(get-nth (- index 1) ; else recurse with the decrement of index
(cdr lst))))) ; and all but the first element (the rest) of lst
;; test
(get-nth 0 '(a)) ; ==> a
(get-nth 1 '(a b)) ; ==> b
;; However, this won't work:
(get-nth 0 '()) ; will fail
(get-nth 10 '(a b c)) ; will fail
我有點喜歡這樣的事實,即如果輸入錯誤的參數,它將無法正常工作。 如果給了錯誤的參數, list-ref
和car
也會失敗,但這很容易解決:
(define get-nth
(lambda (index lst)
(cond ((not (pair? lst)) '()) ; it should always be a pair
((= index 0) (car lst)) ; when index is zero, return the first element
(else (get-nth (- index 1) ; else recurse with the decrement of index
(cdr lst)))))) ; and all but the first element (the rest) of lst
您不僅可以使用默認值,還可以使用(raise'get (raise 'get-nth-error)
(R6RS +)而不是默認值來拋出空列表。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.