Skip to content

Instantly share code, notes, and snippets.

@adamzaninovich
Last active August 29, 2015 14:10
Show Gist options
  • Save adamzaninovich/64fdd0ad72e44d5bf582 to your computer and use it in GitHub Desktop.
Save adamzaninovich/64fdd0ad72e44d5bf582 to your computer and use it in GitHub Desktop.
defmodule Sequence do
def fib(0), do: 1
def fib(1), do: 1
def fib(n), do: fib(n-2) + fib(n-1)
def map([],_f), do: []
def map([head|tail], f) do
[f.(head) | map(tail,f)]
end
def reduce([],_f), do: nil
def reduce([head|tail],f) do
reduce tail, head, f
end
def reduce([],acc,_f), do: acc
def reduce([head|tail],acc,f) do
reduce tail, f.(head, acc), f
end
def filter([],_f), do: []
def filter([head|tail], f) do
if f.(head) do
[head|filter(tail, f)]
else
filter(tail,f)
end
end
def count([]), do: 0
def count([_|t]), do: 1 + count(t)
end
defmodule SequenceTest do
use ExUnit.Case
import Sequence
test "fib" do
assert fib(0) == 1
assert fib(1) == 1
assert fib(10) == 89
end
test "map" do
assert map([4,5,6,7], &(fib &1)) == [5,8,13,21]
end
test "reduce" do
assert reduce([1,2,3], 0, &(&1+&2)) == 6
end
test "reduce with no beginning acc" do
assert reduce([1,2,3], fn (a,b) -> a + b end) == 6
end
test "filter" do
import Integer, only: [is_odd: 1]
assert filter([1,2,3,4], &(is_odd &1)) == [1,3]
end
test "count" do
assert count([:a,:b,:c]) == 3
end
end
@adamzaninovich
Copy link
Author

&(&1 + &2) and fn (a,b) -> a + b end on lines 16 and 20 are equivalent.

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