Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the first index of a given element in Array/List in Elm?

Tags:

arrays

list

elm

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?

like image 604
Misha Moroshko Avatar asked Nov 10 '15 08:11

Misha Moroshko


People also ask

How to find the index of an element in 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).

How to get the first element of an array in JavaScript?

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.

What is ArrayList indexOf in Java?

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.

How do I get the first element of a list?

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.


2 Answers

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

like image 161
Dobes Vandermeer Avatar answered Sep 22 '22 10:09

Dobes Vandermeer


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 ""))    
like image 21
Frank Schmitt Avatar answered Sep 20 '22 10:09

Frank Schmitt