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?
相关问题
- Generating powerset in one function, no explicit r
- What is fixed point?
- How to include another file of definitions in curr
- Forming Lisp code to task — related to flatten lis
- unfold function in scheme
相关文章
- Does learning one Lisp help in learning the other?
- What is “3D syntax”?
- What is the definition of “natural recursion”?
- How do I write a macro-defining macro in common li
- How can I unintern a qualified method?
- Changing the nth element of a list
- sleep in emacs lisp
- How do I define a sub environment in scheme?
Here's a very simple implementation:
And yes, something like this should be added to the standard library, but it's just a little tricky to do so nobody got there yet.
Note, however, that it's a feature that is very rarely useful -- since lists are usually taken as a sequence that is deconstructed using only the first/rest idiom rather than directly accessing elements. More than that, if you have a use for it and you're a newbie, then my first guess will be that you're misusing lists. Given that, the addition of such a function is likely to trip such newbies by making it more accessible. (But it will still be added, eventually.)
One can also use a built-in function '
member
' which gives a sublist starting with the required item or#f
if item does not exist in the list. Following compares the lengths of original list and the sublist returned by member:For many situations, one may want indexes of all occurrences of item in the list. One can get a list of all indexes as follows:
For/list
can also be used for this:Testing:
Output:
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:But there is a similar procedure in
srfi/1
, it's calledlist-index
and you can get the desired effect by passing the right parameters:UPDATE
As of Racket 6.7,
index-of
is now part of the standard library. Enjoy!