Skip to content

Instantly share code, notes, and snippets.

@bullfight
Created September 9, 2014 23:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bullfight/0a703adb5ad6f78c1a50 to your computer and use it in GitHub Desktop.
Save bullfight/0a703adb5ad6f78c1a50 to your computer and use it in GitHub Desktop.
implementation of enum methods in elixir
defmodule Ownum do
def all?([], _fun), do: true
def all?([head | tail], fun) do
if fun.(head) do
all?(tail, fun)
else
false
end
end
def each([], _fun), do: []
def each([head|tail], fun) do
[fun.(head) | each(tail, fun)]
end
def filter([], _fun), do: []
def filter([head|tail], fun) do
if fun.(head) do
[head | filter(tail, fun)]
else
filter(tail, fun)
end
end
def split(list, count) do
do_split(list, [], count)
end
def do_split([], _acc, _count), do: []
def do_split([head|tail], acc, count) do
if length(acc) == count do
[acc, [head|tail]]
else
do_split(tail, acc ++ [head], count)
end
end
def flatten([]), do: []
def flatten([h|t]), do: flatten(h) ++ flatten(t)
def flatten(head), do: [head]
def take(list, count) do
split(list, count) |> hd
end
end
ExUnit.start
defmodule OwnumTest do
use ExUnit.Case, async: true
alias Ownum
def list do
Enum.to_list 1..5
end
test :all? do
assert Ownum.all?(list, &(&1 < 4)) == false
assert Ownum.all?(list, &(&1 <= 5)) == true
end
test :each do
assert Ownum.each([], fn(x) -> x end) == []
assert Ownum.each([1, 2, 3], &(&1 * 2)) == [2,4,6]
end
test :filter do
assert Ownum.filter(list, fn(x) -> rem(x, 2) == 1 end) == [1,3,5]
end
test :split do
assert Ownum.split(list, 3) == [[1,2,3], [4,5]]
end
test :filter do
assert Ownum.flatten([ [1], [ 2, 3, [4] ], 5, [[[6]]]]) == [1,2,3,4,5,6]
end
test :take do
assert Ownum.take(list, 2) == [1,2]
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment