Skip to content

Instantly share code, notes, and snippets.

@cromwellryan
Last active December 19, 2015 22:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save cromwellryan/6024862 to your computer and use it in GitHub Desktop.
Save cromwellryan/6024862 to your computer and use it in GitHub Desktop.
Triangle kata in elixir with some parallel map awesomeness
# gem install guard
# gem install guard-shell
# guard - watch the Magic™
guard 'shell', :elixirc_bin => "/usr/local/elixirc" do
watch(/(.+\.ex$)/) { |m| `elixirc #{m[0]}` }
end
guard 'shell', :elixir_bin => "/usr/local/elixir" do
watch(/(.+\.exs)/) { |m| `elixir #{m[0]}` }
end
defmodule Maps do
def map([], _), do: []
def map([h|t], func), do: [ func.(h) | map(t, func) ]
def child(element, func, parent) do
parent <- func.(element)
end
defp spawn_children(collection, func) do
map collection, fn element -> spawn(__MODULE__, :child, [element, func, self]) end
end
defp collect_results(pids) do
map pids, fn _ -> receive do: ( value -> value) end
end
def pmap(collection, func) do
collection |> spawn_children(func) |> collect_results
end
end
defmodule IClassifyShapes do
defp slow(result, delay) do
:timer.sleep delay
result
end
defp slow(result) do
slow(result, 1000)
end
def classify( {a,b,c} ) when a == b and b == c, do: :equilateral
def classify( {a,b,c} ) when a == b or b == c or a == c, do: slow(:isosceles, 1100)
def classify( {a,b,c} ) when a != b and b != c, do: slow(:scalene)
def classify( [h|t] ), do: [classify(h) | classify(t)]
def classify( [] ) do
IO.puts 'asdf'
[]
end
def classify( _ ), do: :unclassified
end
triangles = [
"blue",
{ 9, 10, 11 },
{ 9, 10, 11 },
{ 9, 10, 11 },
{ 9, 10, 11 },
{ 9, 10, 11 },
{ 9, 10, 11 },
{ 9, 10, 11 },
{ 10, 11, 11 },
{ 10, 11, 10 },
{ 11, 11, 10 },
{ 12, 12, 12 },
]
IO.inspect triangles |> Maps.pmap fn x -> IClassifyShapes.classify(x) end
@cromwellryan
Copy link
Author

You might ask why the slow block around scalene and isosceles. I did that to validate the asynchrony. Take it out if it pleases you.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment