Skip to content

Instantly share code, notes, and snippets.

@stockwellb
Last active June 8, 2016 01:14
Show Gist options
  • Save stockwellb/6fd8732784329339b85e0ac7e926d9dc to your computer and use it in GitHub Desktop.
Save stockwellb/6fd8732784329339b85e0ac7e926d9dc to your computer and use it in GitHub Desktop.
And-ing and Or-ing list elements
defmodule ListTruther do
def test([],_) do
false
end
def test(list, mode) do
case mode do
:and -> Enum.reduce_while(list, false, fn(item, _) ->
if item, do: {:cont, true}, else: {:halt, false}
end)
:or -> Enum.reduce_while(list, false, fn(item, _) ->
unless item, do: {:cont, false}, else: {:halt, true}
end)
end
end
end
ExUnit.start
defmodule ListTrutherTest do
use ExUnit.Case, async: true
test "list_and empty list is false" do
assert false == ListTruther.test([], :and)
end
test "list_and; all false" do
assert false == ListTruther.test([false, false, false], :and)
end
test "list_and; all true" do
assert true == ListTruther.test([true, true, true], :and)
end
test "list_and; not all false" do
assert false == ListTruther.test([true, false, true], :and)
end
test "list_or; empty list is false" do
assert false == ListTruther.test([], :or)
end
test "list_or; all false" do
assert false == ListTruther.test([false, false, false], :or)
end
test "list_or; all true" do
assert true == ListTruther.test([true, true, true], :or)
end
test "list_or; not all true" do
assert true == ListTruther.test([true, false, true], :or)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment