Skip to content

Instantly share code, notes, and snippets.

@jamiecurle

jamiecurle/foo.exs

Created Apr 26, 2017
Embed
What would you like to do?
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
You can’t perform that action at this time.