Last active
December 19, 2015 22:08
-
-
Save cromwellryan/6024862 to your computer and use it in GitHub Desktop.
Triangle kata in elixir with some parallel map awesomeness
This file contains 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
# 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 |
This file contains 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
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 |
This file contains 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
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 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.