Skip to content

Instantly share code, notes, and snippets.

@kdxu
Created October 3, 2016 09:09
Show Gist options
  • Save kdxu/45a1e9c7727eda0158ee988dbb0026a6 to your computer and use it in GitHub Desktop.
Save kdxu/45a1e9c7727eda0158ee988dbb0026a6 to your computer and use it in GitHub Desktop.
defmodule MyList do
def len([]), do: 0
def len([_head | tail]), do: 1 + len(tail)
def square([]), do: []
def square([head | tail]), do: [head*head | square(tail)]
def map([], _func), do: []
def map([head | tail], func), do: [func.(head) | map(tail, func)]
def sum(list), do: _sum(list, 0)
# private function
defp _sum([], total), do: total
defp _sum([head | tail], total), do: _sum([tail], head + total)
def reduce([], value, _) do
value
end
def reduce([head | tail], value, func) do
reduce(tail, func.(head, value), func)
end
def mapsum(list, func) do
reduce(map(list, func), 0, (&(&1 + &2)))
end
def max([]), do: 0
def max([head | tail]), do: reduce([head | tail], head, &(compare(&1, &2)))
def compare(p1, p2) when p1 > p2, do: p1
def compare(p1, p2) when p1 <= p2, do: p2
def caesar(list, n) do
map(list, fn x -> _decode_char(x, n) end)
end
defp _decode_char(char, num) when char + num > 122 do
char + num - 26
end
defp _decode_char(char, num) when char + num < 122 do
char + num
end
def span(from, to) when from < to do
[from | span(from + 1, to)]
end
def span(from, to) when from == to, do: [to]
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment