Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!
  • Rust

Idiom #222 Find the first index of an element in list

Set i to the first index in list items at which the element x can be found, or -1 if items does not contain x.

let opt_i = items.iter().position(|y| *y == x);


let i = match opt_i {
   Some(index) => index as i32,
   None => -1
};

The first line is ideomatic Rust and allows you to work with an Option.

The rest is some (potentially useless/ugly) implementation of "returning -1"
let i = items.iter().position(|y| *y == x).map_or(-1, |n| n as i32);

Rust uses the usize type to index lists, but it can't be negative. We need to manually convert it to an i32 to be able to return -1
(defn find-index [x items]
  (reduce-kv
    #(if (= x %3) (reduced %2) %1) -1 items))

Clojure already provides some iteration functions to be used with the concept of reduction

New implementation...
programming-idioms.org