如何访问球拍列表中的特定位置

时间:2018-10-22 05:04:35

标签: list recursion racket

我在获取所需列表的位置时遇到问题。 我不确定要用什么来从要求的位置获取价值。 如果是python,我可以重复多次(fist(rest n),但是我对这里的球拍感到困惑。

(check-expect (get-char "abcdefg" 0) #\a)
(check-expect (get-char "abcdefg" 3) #\d)
(check-expect (get-char "abcdefg" 20) #\*)
(define (list-of-char string-input)
  (string->list string-input))
(define (get-char string-input position)
  (cond [(empty? (list-of-char string-input)) #\*]
        [(> position (string-length string-input)) #\*]
        [else (cond
                [
                   [else (get-char (rest (list-of-char string-input)) position)])])

1 个答案:

答案 0 :(得分:2)

您的代码中有几个错误。对于初学者,在进行递归时应降低位置,并且一开始只应将字符串转换为列表一次。

此外,您没有正确检查是否达到预期的位置-剩余长度与您要查找的位置不相等。最后的else/cond/else部分没有意义,并且括号太多。

Scheme中从头开始的解决方案通常会使用命名的let进行递归,但是为了简单起见,我将使用辅助程序:

(define (get-char string-input position)
  ; convert to a list only once at the beginning
  (loop (string->list string-input) position))

(define (loop list-of-char position)
        ; there are two exit conditions we need to check
  (cond [(or (empty? list-of-char)
             (negative? position)) #\*]
        ; we found the element
        [(zero? position) (first list-of-char)]
        ; keep looking
        [else (loop (rest list-of-char) (sub1 position))]))

我们可以使用内置过程编写一个更惯用的解决方案:

(define (get-char string-input position)
  (if (or (negative? position)
          (>= position (string-length string-input)))
      #\*
      (string-ref string-input position)))

无论哪种方式,它都能按预期工作:

(get-char "abcdefg" -1)
; => #\*

(get-char "abcdefg" 0)
; => #\a

(get-char "abcdefg" 3)
; => #\d

(get-char "abcdefg" 6)
; => #\g

(get-char "abcdefg" 7)
; => #\*