Skip to content

Instantly share code, notes, and snippets.

@treejamie
Created April 26, 2017 11:42
Show Gist options
  • Save treejamie/00811406f7c34f7adc6fce2d922b372a to your computer and use it in GitHub Desktop.
Save treejamie/00811406f7c34f7adc6fce2d922b372a to your computer and use it in GitHub Desktop.
defmodule Foo do
@doc """
Returns sum of items in a list
"""
def sum(list), do: _sum(list, 0)
defp _sum([], acc), do: acc
defp _sum([h|t], acc), do: _sum(t, h + acc)
@doc """
Custom map function
"""
def map2([], _), do: []
def map2([h|t], func) do
[func.(h) | map2(t, func)]
end
@doc """
Fizzbuzz implementation
"""
def fizzbuzz(x) when is_list(x) do
Enum.map(x, &fizzbuzz/1)
end
def fizzbuzz(x) when is_integer(x) and rem(x, 3) == 0 and rem(x, 5) == 0, do: IO.puts "FizzBuzz"
def fizzbuzz(x) when is_integer(x) and rem(x, 3) == 0, do: IO.puts "Fizz"
def fizzbuzz(x) when is_integer(x) and rem(x, 5) == 0, do: IO.puts "Buzz"
def fizzbuzz(x) when is_integer(x), do: IO.puts x
@doc """
palindrome predicate
"""
def palindrome?(word) do
word == Enum.reduce(word |> String.graphemes, "", &(&1 <> &2))
end
end
IO.puts "FizzBuzz >>"
Foo.fizzbuzz(1..30 |> Enum.to_list) |> IO.inspect
IO.puts "sum >>"
Foo.sum(1..10 |> Enum.to_list) |> IO.inspect
IO.puts "map >>"
Foo.map2(1..10 |> Enum.to_list, &(&1 * 2)) |> IO.inspect
IO.puts "palindrome? >>"
Enum.map(["racecar", "dog", "tenet"], &Foo.palindrome?/1) |> IO.inspect
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment