hipertracker
Idiomatic Elixir for collecting last item from dynamic list
How to write idiomatic Elixir for the following code in Ruby? The main difficulty here is that the immutable language cannot accumulate items in such way: if my current item does not meet the condition than I want to get the last item which did it before.
result = []
items.each do |item|
if condition(item)
result << {value: item, flag: :ok}
else
result << {value: result.last, flag: :previous}
end
end
UPDATE: I had an error in the code. I have to find last item from result list.
First Post!
bbense
There’s a couple approaches, if items is always a List, you can write your own reduction. If it might be something else that is still Enumerable, you’ll need to use Enum.reduce. Basically, all “looping” is done with reductions that peel off the head of the loop and then call the function on the tail. If you need state from a previous loop, you put
that in an “acc” or accumulator argument.
Here’s a list based version
def last_true( [], acc, check_fn) do
acc
end
def last_true( [ head | tail ], acc, check_func ) do
case check_func(h) do
true -> new_ acc = [ %{value: head, flag: :ok} | acc ]
- -> [ prev_item | _rest ] = acc
new_acc = [ Map.put(prev_item, :flag, :previous) | acc ]
end
last_true( tail, new_acc, check_func)
end
Depending on exactly what you want to do, you might need to reverse the output of last_true at this point. There is an optimized erlang function for this case. :lists.reverse. You would call last_true something like this.
results = last_true(items, [] , &check_fun/1 )
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #advent-of-code
- #elixirconf-us
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #performance








