defmodule Demo do
def max_by_with_value(items,fun) do
with_compare_result = fn i -> {i, fun.(i)} end
compare_result = fn {_,result} -> result end
items
|> Enum.map(with_compare_result)
|> Enum.max_by(compare_result)
end
def foldl_impl([x|xs],fun) do
f = fn (x, {_,value} = last) ->
result = fun.(x)
if result > value, do: {x,result}, else: last
end
List.foldl(xs, {x, fun.(x)}, f)
end
end
fun = &(&1 |> String.graphemes() |> length())
items = ["a", "aaa", "aa"]
IO.inspect Demo.max_by_with_value(items, fun)
IO.inspect Demo.foldl_impl(items, fun)