In Javascript, one could use indexOf to get the first instance of a given element in an array.
What's the best way to do this in Elm?
array = Array.fromList ["Stack","Overflow","is","","awesome"]
element = ""
indexOf element array =
-- should return 3
What if we have a list instead of an array?
Java provides us with an inbuilt function which can be found in the Arrays library of Java which will return the index if the element is present, else it returns -1. The complexity will be O (log n).
Array index always starts with index=0 and array.length returns the length of an array. that means array [0] returns first element, array [array.length-1] returns last element of an array. Array.length property returns the length of an array. Following are Multiple ways, we can retrieve the first element of an array in JavaScript.
ArrayList.indexOf () method This method returns the index of the first occurrence of the specified element in this list. It will return '-1' if the list does not contain the element.
You can specify index as 0 to get the first element of the List. In this article, we're exploring get () method usage via multiple examples. Returns the element at the specified position.
There is a third party module elm-list-extra that provides this function. "elemIndex" (works for 0.19).
And this one for < 0.19 elemIndex
Just for fun, here's a hand-rolled version for List:
helper : List a -> a -> Int -> Int
helper lst elem offset =
case lst of
[] -> -1
x :: xs ->
if x == elem then offset
else helper xs elem (offset + 1)
indexOf lst element =
helper lst element 0
helper
recursively searches the list for the element, keeping track of the number of elements we've visited so far. For the empty list, it returns -1.
If you don't like magic constants, you could easily change the return type to Maybe Int
and return Nothing
instead.
And here's a complete program using it (just copy + paste into the online REPL at elm-lang.org:
import Html exposing (text)
lst = ["Stack","Overflow","is","","awesome"]
element = ""
helper : List a -> a -> Int -> Int
helper lst elem offset =
case lst of
[] -> -1
x :: xs ->
if x == elem then offset
else helper xs elem (offset + 1)
indexOf lst element =
helper lst element 0
main =
text (toString (indexOf lst ""))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With