从一个方法调用一个方法

Call a method from a method

我是 Racket 的新手。我正在尝试编写一个程序 return 列表中的索引元素,return 整个列表。我有两种不同的方法:一种递归方法,如果存在则给出列表的索引元素,否则给出整个列表。但是,从另一种方法调用一种方法会给我错误。如果存在 none 个索引元素,有人可以指导我如何更改此程序以提供整个列表吗?例如这个电话应该给我整个列表

(get-nth 2 '(a b)) ; ==> 一个 b

#lang racket
(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

提前致谢,

为此,您必须将原始列表存储在某处。为了避免不必要的辅助函数,我们可以使用命名的 let 来实现迭代,而当我们必须 return 时,不用管原来的 lst 。当然,我们 必须 测试我们 运行 元素不足的情况,因为给定的索引在列表之外。这就是我的意思:

(define get-nth
  (lambda (index lst)
    (let loop ((index index) (my-list lst))
      (cond ((null? my-list) lst)
            ((= index 0) (car my-list))
            (else (loop (- index 1) (cdr my-list)))))))

例如:

(get-nth 0 '(a b))
=> 'a

(get-nth 2 '(a b)) 
=> '(a b)