繁体   English   中英

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

[英]How access a specific position in racket list

我在获取所需列表的位置时遇到问题。 我不确定要用什么来从要求的位置获取价值。 如果是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)])])

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

另外,您没有正确检查是否达到了预期的位置-剩余长度与您要查找的位置不相等。 最后的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)
; => #\*

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM