fork download
  1. defmodule LinearSearch do
  2. def search(list, target) do
  3. search_index(list, target, 0)
  4. end
  5.  
  6. defp search_index([], _target, _index), do: nil
  7. defp search_index([head | tail], target, index) do
  8. if head == target do
  9. index
  10. else
  11. search_index(tail, target, index + 1)
  12. end
  13. end
  14. end
  15.  
  16. arr = [41242, 1, 2263, 411, 9112]
  17. target = 411
  18.  
  19. case LinearSearch.search(arr, target) do
  20. nil -> IO.puts("The element #{target} was not found")
  21.  
  22. index -> IO.puts("The element #{target} was found at position #{index + 1}")
  23. end
Success #stdin #stdout 0.5s 41140KB
stdin
Standard input is empty
stdout
The element 411 was found at position 4