Skip to content

Instantly share code, notes, and snippets.

@gowrizrh
Last active October 22, 2024 23:10
Show Gist options
  • Select an option

  • Save gowrizrh/0d2aa169bccb8de8a3916a6f40ae3f9f to your computer and use it in GitHub Desktop.

Select an option

Save gowrizrh/0d2aa169bccb8de8a3916a6f40ae3f9f to your computer and use it in GitHub Desktop.

Revisions

  1. gowrizrh revised this gist Oct 22, 2024. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion main.exs
    Original file line number Diff line number Diff line change
    @@ -1,4 +1,4 @@
    # Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
    # binary pattern matching, return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

    defmodule Main do
    def str_str(haystack, needle) do
  2. gowrizrh created this gist Oct 15, 2024.
    27 changes: 27 additions & 0 deletions main.exs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,27 @@
    # Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

    defmodule Main do
    def str_str(haystack, needle) do
    match(haystack, needle, 0)
    end

    def match(<<s, str::binary>>, <<s, needle::binary>>, index) do
    needle_len = needle |> String.length()

    if str |> String.slice(0, needle_len) == needle do
    index
    else
    match(str, <<s>> <> needle, index + 1)
    end
    end

    def match(<<s, str::binary>>, <<c, needle::binary>>, index) do
    match(str, <<c>> <> needle, index + 1)
    end

    def match(_, _, _) do
    -1
    end
    end

    Main.str_str("Parapsychology", "psychology") |> IO.inspect()