Created
October 5, 2022 05:54
-
-
Save mavuio/6eac81cec962fdf903705f0b5ca44535 to your computer and use it in GitHub Desktop.
elixir early return/exit from loop/comprehesion/while/each #elixir
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# I found Stream.unfold to be quite useful for places where I don’t know how many iterations are #needed to get to the end. | |
Stream.unfold([], fn words -> | |
if length(words) < target_length do | |
words = | |
(words ++ get_new_words()) | |
|> Enum.uniq() | |
{new_words, words} | |
else | |
nil | |
end | |
end) | |
|> Enum.to_list() | |
|> List.last() | |
|> Enum.take(target_length) | |
Stream.run(stream) | |
# There’s also Enum.reduce_while, but it needs an enumerable as input to start with: | |
Enum.reduce_while(1..100, [], fn _, acc -> | |
if length(acc) < target_length do | |
{:ok, new_words} = get_words_from_ai(config_key) | |
new_acc = | |
(acc ++ new_words) | |
|> Enum.uniq() | |
{:cont, new_acc} | |
else | |
{:halt, acc} | |
end | |
end) | |
|> case do | |
words when length(words) >= target_length -> {:ok, Enum.take(words, target_length)} | |
_ -> {:error, []} | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment