如何在Racket中的列表中找到元素的索引? [英] How do I find the index of an element in a list in Racket?
问题描述
这当然是微不足道的工具,但我觉得Racket肯定内置了某些功能.我的直觉是正确的吗?如果是,函数是什么?
This is trivial implement of course, but I feel there is certainly something built in to Racket that does this. Am I correct in that intuition, and if so, what is function?
推荐答案
奇怪的是,Racket中没有内置的过程可以在列表中查找元素的从0开始的索引(相反的过程是否存在,它称为
Strangely, there isn't a built-in procedure in Racket for finding the 0-based index of an element in a list (the opposite procedure does exist, it's called list-ref
). However, it's not hard to implement efficiently:
(define (index-of lst ele)
(let loop ((lst lst)
(idx 0))
(cond ((empty? lst) #f)
((equal? (first lst) ele) idx)
(else (loop (rest lst) (add1 idx))))))
But there is a similar procedure in srfi/1
, it's called list-index
and you can get the desired effect by passing the right parameters:
(require srfi/1)
(list-index (curry equal? 3) '(1 2 3 4 5))
=> 2
(list-index (curry equal? 6) '(1 2 3 4 5))
=> #f
更新
As of Racket 6.7, index-of
is now part of the standard library. Enjoy!
这篇关于如何在Racket中的列表中找到元素的索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!