Last active
October 22, 2024 23:10
-
-
Save gowrizrh/0d2aa169bccb8de8a3916a6f40ae3f9f to your computer and use it in GitHub Desktop.
Revisions
-
gowrizrh revised this gist
Oct 22, 2024 . 1 changed file with 1 addition and 1 deletion.There are no files selected for viewing
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 charactersOriginal file line number Diff line number Diff line change @@ -1,4 +1,4 @@ # 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 -
gowrizrh created this gist
Oct 15, 2024 .There are no files selected for viewing
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 charactersOriginal 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()