【问题标题】:Trying to get the indices of an element from a list in scheme试图从方案中的列表中获取元素的索引
【发布时间】:2011-07-18 21:24:10
【问题描述】:

所以我正在尝试从列表中获取索引:

(get-indices 'G (list 'A 'G 'T 'X 'I 'T 'G))

(2 7)

索引从 1 开始,所以 'A 是索引 1

我正在考虑使用一个辅助函数,它需要一个 elt lst 和索引 例如:(get-indices-helper el lst 索引)

我也在考虑可能使用 list-ref 并喜欢切换它以使其以获取索引的方式工作,但是我找不到它的实际方案定义。

【问题讨论】:

    标签: list function helper indices


    【解决方案1】:

    编写一个递归输入列表的函数,跟踪它正在查看的元素的位置,并使用cons 发出匹配的索引。这真的很微不足道;我假设这是你被设置为家庭作业的问题?

    ; Walk down the list given in haystack, returning a list of indices at which
    ; values equal? to needle appear.
    (define (get-indices needle haystack)
      ; Loop along the haystack.
      (define (loop rest-of-haystack index)
        ; If the haystack is empty, return the empty list.
        (if (null? rest-of-haystack) '()
          ; Recurse to the next position in the list.
          (let ((rest-of-indices (loop (cdr rest-of-haystack) (+ index 1))))
            (if (equal? (car rest-of-haystack) needle)
              ; If haystack is here, emit the current index.
              (cons index rest-of-indices)
              ; Otherwise, return rest-of-indices.
              rest-of-indices))))
      ; Run the loop defined above, from the beginning of haystack, with
      ; the first element being assigned an index of 1.
      (loop haystack 1))
    

    用 GNU Guile 或 MzScheme 或其他东西对此进行测试:

    (display (get-indices 'G (list 'A 'G 'T 'X 'I 'T 'G))) (newline)
    (display (get-indices 1 (list 1 1 1 2 1 3))) (newline)
    

    打印:

    (2 7)
    (1 2 3 5)
    

    耶!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-12-03
      • 1970-01-01
      • 1970-01-01
      • 2020-07-27
      • 2019-03-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多