【问题标题】:How access a specific position in racket list如何访问球拍列表中的特定位置
【发布时间】:2019-03-26 03:15:42
【问题描述】:

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

【问题讨论】:

  • 在 Racket 中,我们也会重复 rest 给定的次数,只是我们使用递归来完成。

标签: list recursion racket


【解决方案1】:

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

此外,您没有正确检查是否到达了预期位置 - 剩余长度不等于您希望找到的位置。并且末尾的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)
; => #\*

【讨论】:

    猜你喜欢
    • 2019-10-29
    • 2021-05-30
    • 1970-01-01
    • 2015-08-26
    • 2014-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多