Skip to content

Instantly share code, notes, and snippets.

@AlbertMoscow
Forked from mattyw/pierre.exs
Last active December 18, 2015 05:39
Show Gist options
  • Save AlbertMoscow/5734487 to your computer and use it in GitHub Desktop.
Save AlbertMoscow/5734487 to your computer and use it in GitHub Desktop.
# Inspired by:
# http://learnyouahaskell.com/a-fistful-of-monads#walk-the-line
# Put simply, pierre is a tight rope walker. birds land on the left
# or right of his pole. If the difference is > 3 he falls off
ExUnit.start
defmodule WalkTheLine do
use ExUnit.Case
def landLeft({l, r}, n) when abs((l + n) - r) > 3 do
:felloff
end
def landLeft(:felloff, _) do
:felloff
end
def landLeft({l, r}, n) do
{l + n, r}
end
def landRight({l, r}, n) when abs((r + n) - l) > 3 do
:felloff
end
def landRight(:felloff, _) do
:felloff
end
def landRight({l, r}, n) do
{l, r + n}
end
test "nasty syntax" do
assert {5,4} == landRight(landLeft(landRight(landLeft({0,0}, 3), 3), 2), 1)
end
test "using the pipe operator" do
assert {5,4} == {0,0} |> landLeft(3) |> landRight(3) |> landLeft(2) |> landRight(1)
end
# ok so far, but we don't deal with failure
# for failure we're going to return :felloff
test "testing for failure" do
assert :felloff == {0,0} |> landLeft(3) |> landRight(3) |> landLeft(8) |> landRight(2)
end
test "correct testing for failure" do
assert :felloff == {0,0} |> landLeft(1) |> landRight(4) |> landLeft(-1) |> landRight(-2)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment