Хабр Курсы для всех
РЕКЛАМА
Практикум, Хекслет, SkyPro, авторские курсы — собрали всех и попросили скидки. Осталось выбрать!
List.foldl([5,5], 10, fn (x, acc) -> x + acc end):lists.foldl(fn({a, b}, acc) ->
c = case a > b do
true -> a * 2
false -> b * 3
end
acc + c + 1
end, 0, [{1,2},{3, 4}])List.foldl([{1, 2}, {3, 4}], 0, fn({a, b}, acc) ->
c = case a > b do
true -> a * 2
false -> b * 3
end
acc + c + 1
end)List.foldl([5,5], 10, fn (x, acc) ->
x + acc
end)List.foldl([5,5], 10, &1 + &2) A couple notes:
1) The majority of erlang modules (array, binary, re, gen_*, file, diagraph, ets, etc) actually expect the subject as first argument. lists, *dict and string are the exception and not the rule. Since Elixir provides a better alternative for those (Enum which supports any Enumerable instead of lists, faster dicts, proper utf-8 strings, etc), you won't use the Erlang ones. So it is very likely that whatever module you use, in Erlang or Elixir, you will have the subject as first argument convention.
2) Leaving the subject as last argument may make optional arguments more confusing since the last argument position changes based on the arity. One similar example of this oddity is element and setelement in Erlang stdlib, where element writes like element(index, tuple) and setelement(index, tuple, value). So it is the last except when it isn't?
3) Having the subject as the first argument also works nicely with protocols which detect the target implementation using the first argument. Protocols would be *very* confusing if the target was based on the last argument.
4) Finally, I personally prefer the function to come as last argument for readability issues. The example below reads as «I want to map this collection by calling do_something on each item»:
Enum.map collection, fn(x) -> do_something(x) end
However, by changing the order, you get «I want to map by calling do something on each item this collection»:
Enum.map fn(x) -> do_something(x) end, collection
It feels unnatural imo. Also, the variable name may give good hints on what you are enumerating, which comes too late when it is the last argument.
Besides, having the function as last argument reads better for multiline functions:
Enum.map collection, fn(x) ->
do_something(x)
end
So if we are calling it a design mistake, I would say it was very premeditated one. :)
|> передает результат как первый аргумент.sum = foldl + 0
sum = foldl + 0
def mysum(list, acc // 0) do
....
endsum = List.foldl(&1, 0, &1 + &2)
sum.([1,2,3,4,5])sum = :lists.foldl(&1 + &2 0, &1)
sum.([1,2,3,4,5])консоли elixir-а можно создавать модули и кортежиКортежи? Может рекорды?
Правильно понимаю, что в последней строчке неEnum.map(list, fn({a, x}) -> {a, x * 2} end) dict = HashDict.New(list) Enum.map(list, fn({a, x}) -> {a, x * 2} end)
map(list, а map(dict?
Elixir