Last active
October 22, 2024 23:10
-
-
Save gowrizrh/0d2aa169bccb8de8a3916a6f40ae3f9f to your computer and use it in GitHub Desktop.
Elixir Snippets
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 | |
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() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment