Skip to content

Instantly share code, notes, and snippets.

@mattyw
Last active December 18, 2015 04:19
Show Gist options
  • Save mattyw/5724987 to your computer and use it in GitHub Desktop.
Save mattyw/5724987 to your computer and use it in GitHub Desktop.
Walk the line from http://learnyouahaskell.com/a-fistful-of-monads#walk-the-line done in elixir. The first version shows the advantage of the pipe operator. The update shows us testing for preconditions with 'when' and also using patten matching to make the landleft and right functions easier to read.
# 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 ((l + n) - r) > 4 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 ((r + n) - l) > 4 do
:felloff
end
def landright(:felloff, _) do
:felloff
end
def landright({l, r}, n) do
{l, r + n}
end
# We will test:
# landleft(3)
# landright(3)
# landleft(2)
# landright(2)
# assert pierre == 5
test "nasty syntax" do
assert {5,5} == landright(landleft(landright(landleft({0,0}, 3), 3), 2), 2)
end
test "using the pipe operator" do
assert {5,5} == {0, 0} |> landleft(3) |> landright(3) |> landleft(2) |> landright(2)
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
end
@AlbertMoscow
Copy link

According to original source the following call
{0,0} |> landLeft(1) |> landRight(4) |> landLeft(-1) |> landRight(-2)
should lead to :felloff

See corrections in my fork.

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