Elixir 練習問題 ListsAndRecursion-3

今度の練習問題はカエサル暗号だ。

defmodule MyList do

  def map([], _func), do: []
  def map([head|tail], func), do: [func.(head) | map(tail, func)]

  def reduce([], value, _func) do
    value
  end
  def reduce([head|tail], value, func) do
    reduce(tail, func.(head, value), func)
  end

  def caesar(list, n) do
    map(list, fn c -> rem(c + n - ?a, 26) + ?a end)
  end

end
^o^ > iex practice_7_3.exs
Eshell V8.0  (abort with ^G)
Interactive Elixir (1.3.4) - press Ctrl+C to exit (type h() ENTER for help)
iex(1)> MyList.caesar('ryvkve', 13)
'elixir'

Elixir 練習問題 ListsAndRecursion-2

defmodule MyList do

  def reduce([], value, _func) do
    value
  end
  def reduce([head|tail], value, func) do
    reduce(tail, func.(head, value), func)
  end

  def max([head|tail]) do
    reduce(tail, head, &_max/2)
  end

  defp _max(a, b) when a < b, do: b
  defp _max(a, _), do: a

end
^o^ > iex practice_7_2.exs
Eshell V8.0  (abort with ^G)
Interactive Elixir (1.3.4) - press Ctrl+C to exit (type h() ENTER for help)
iex(1)> MyList.max([1,2,3,4,5])
5
iex(2)> MyList.max([5,4,3,2,1])
5