Copy Enum while_ok utils from SPARQL.Client

This commit is contained in:
Marcel Otto 2020-09-30 12:45:33 +02:00
parent 96bb678ffc
commit aed8e5bae6
2 changed files with 30 additions and 9 deletions

View file

@ -4,6 +4,7 @@ defmodule RDF.Query.Builder do
alias RDF.Query.BGP
alias RDF.{IRI, BlankNode, Literal, Namespace}
import RDF.Utils.Guards
import RDF.Utils
def bgp(query) do
with {:ok, triple_patterns} <- triple_patterns(query) do
@ -19,15 +20,10 @@ defmodule RDF.Query.Builder do
end
defp triple_patterns(query) when is_list(query) do
Enum.reduce_while(query, {:ok, []}, fn
triple, {:ok, triple_patterns} ->
case triple_pattern(triple) do
{:ok, triple_pattern} ->
{:cont, {:ok, triple_patterns ++ List.wrap(triple_pattern)}}
{:error, error} ->
{:halt, {:error, error}}
end
flat_map_while_ok(query, fn triple ->
with {:ok, triple_pattern} <- triple_pattern(triple) do
{:ok, List.wrap(triple_pattern)}
end
end)
end

View file

@ -13,4 +13,29 @@ defmodule RDF.Utils do
:erlang.error({:badmap, other}, [map, key, init_fun, fun])
end
end
def map_while_ok(enum, fun) do
with {:ok, mapped} <-
Enum.reduce_while(enum, {:ok, []}, fn e, {:ok, acc} ->
with {:ok, value} <- fun.(e) do
{:cont, {:ok, [value | acc]}}
else
error -> {:halt, error}
end
end) do
{:ok, Enum.reverse(mapped)}
end
end
def flat_map_while_ok(enum, fun) do
with {:ok, mapped} <- map_while_ok(enum, fun) do
{:ok, Enum.concat(mapped)}
end
end
def map_join_while_ok(enum, joiner \\ "", fun) do
with {:ok, mapped} <- map_while_ok(enum, fun) do
{:ok, Enum.join(mapped, joiner)}
end
end
end