返回首页 - Notes - 2015

用 Elixir 实现 map


写法一

defmodule Test do

  def map(list, ff), do: map(list, ff, []) |> reverse
  defp map([], _, result), do: result
  defp map([h|t], ff, result), do: map(t, ff, [ff.(h)|result])

  def reverse(list), do: reverse(list, [])
  defp reverse([], result), do: result
  defp reverse([h|t], result), do: reverse(t, [h|result])

end


list = Enum.to_list 1..10
IO.inspect Test.map(list, &(&1 * &1))

写法二

defmodule Test do

  def map(list, ff, result \\ []) do
    case list do
      [] -> result
      [h|t] -> map(t, ff, [ff.(h)|result])
    end |> reverse
  end

  def reverse(list, result \\ []) do
    case list do
      [] -> result
      [h|t] -> reverse(t, [h|result])
    end
  end

end


list = Enum.to_list 1..10
IO.inspect Test.map(list, &(&1 * &1))

写法三

map = &(&4.(case &1 do
  [] -> &2
  [h|t] -> &3.(t, [&5.(h)|&2], &3, &4, &5)
end, [], &4))


reverse = &(case &1 do
  [] -> &2
  [h|t] -> &3.(t, [h|&2], &3)
end)


list = Enum.to_list 1..10
IO.inspect map.(list, [], map, reverse, &(&1 * &1))

写法四

map = &(&4.(case &1 do
  [] -> &2
  [h|t] -> &3.(t, [&5.(h)|&2], &3, &4, &5)
end, [], &4))


list = Enum.to_list 1..10
IO.inspect map.(list, [], map, &(case &1 do
  [] -> &2
  [h|t] -> &3.(t, [h|&2], &3)
end), &(&1 * &1))

写法五

list = Enum.to_list 1..10


IO.inspect (&(&4.(case &1 do
  [] -> &2
  [h|t] -> &3.(t, [&5.(h)|&2], &3, &4, &5)
end, [], &4))).(list, [], &(&4.(case &1 do
  [] -> &2
  [h|t] -> &3.(t, [&5.(h)|&2], &3, &4, &5)
end, [], &4)), &(case &1 do
  [] -> &2
  [h|t] -> &3.(t, [h|&2], &3)
end), &(&1 * &1))

写法六

defmodule Test do

  def map(list, ff), do: _map(list, ff, [])
  defp _map([], _, ret), do: ret
  defp _map([h|t], ff, ret), do: _map(t, ff, ret ++ [ff.(h)])

end


list = Enum.to_list(0..10)
IO.inspect Test.map(list, &(&1 * &1))

date:2015-11-26、2015-11-30