Skip to content

Instantly share code, notes, and snippets.

@parndt
Last active June 7, 2016 23:56
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 parndt/480566146165253a62ea4bcdcc3ea64d to your computer and use it in GitHub Desktop.
Save parndt/480566146165253a62ea4bcdcc3ea64d to your computer and use it in GitHub Desktop.
defmodule MyList do
def square([]), do: []
def square([ head | tail]), do: [ head * head | square(tail) ]
def add_1([]), do: []
def add_1([ head | tail ]), do: [ head + 1 | add_1(tail) ]
def map([], _func), do: []
def map([head | tail], func), do: [ func.(head) | map(tail, func) ]
def reduce([], value, _), do: value
def reduce([head | tail], value, func) do
reduce tail, func.(head, value), func
end
def mapsum(list, func) do
sum map(list, func)
end
def max([single]), do: single
def max([head | tail]), do: Kernel.max(head, max(tail))
def min([single]), do: single
def min([head | tail]), do: Kernel.min(head, min(tail))
def caesar(list, n) do
map list, fn char ->
rem(char - ?a + n, (?z - ?a + 1)) + ?a
end
end
# with accumulator, but hidden.
def sum(list), do: _sum(list, 0)
defp _sum([], total), do: total
defp _sum([head | tail], total), do: _sum(tail, head + total)
# without accumulator.
def sum([]), do: 0
def sum([head | tail]), do: head + sum(tail)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment