dokuzbir

dokuzbir

Is there a better way to handle :ok tuples?

  (fn ->
     {:ok, naive_date_time} =
       NaiveDateTime.new(Date.utc_today(), (fn -> {:ok, time} = Time.new(3, 2, 00); time end).() )
     naive_date_time
   end).(),

I have that ugly code multiple functions return {:ok, what_i_need } tuple. That is why i use anonymous functions is there better way handle :ok tuples?

Most Liked

peerreynders

peerreynders

In my mind that is “sloppy typing” - always returning a two element tuple where the consistently typed value of the first element is an indication of the type of the second value is much cleaner - and I suspect much better for pattern matching.

The :ok/:error tuple is a poor man’s implementation of Either. When used correctly it makes it easier to compose functions without having to specify explicit conditionals to deal with the errors - i.e. it enables railway-oriented programming (ROP).

defmodule Demo  do

  def f1({hour, minute, second}),
    do: Time.new(hour, minute, second)

  def f2({:ok, time}),
    do: NaiveDateTime.new(Date.utc_today(), time)
  def f2(other),
    do: other

  def f3(input),
    do: input
        |> f1()
        |> f2()

end

IO.inspect(Demo.f3({3,2,0}))
IO.inspect(Demo.f3({25,2,0}))
$ elixir demo.exs
{:ok, ~N[2018-05-12 03:02:00]}
{:error, :invalid_time}

peerreynders

peerreynders

In any case - what exactly is stopping you from putting the “ugly code” into a stand-alone, clearly-named function?

NobbZ

NobbZ

But what if {:error, _} is a legit return value? How would you distinguish this from a real error?

Consider an Elixir Term Parser: Terms.parse("{:error, :badarg}").

If we were returning plain values on success but {:error, :badarg} on non-string input, we had a problem here.

But since it is common to return wrapped values in success cases, we can clearly and unambiguisly distinguish between {:ok, {:error, :badarg}} and {:error, :badarg}.


I do not understand your reasoning, seems to work:

iex(1)> for x <- 1..10 do
...(1)>   {:ok, time} = Time.new(3, 2, 0) 
...(1)>   {:ok, naive} = NaiveDateTime.new(Date.utc_today(), time)
...(1)>   %{date_time: naive}
...(1)> end
[
  %{date_time: ~N[2018-05-12 03:02:00]},
  %{date_time: ~N[2018-05-12 03:02:00]},
  %{date_time: ~N[2018-05-12 03:02:00]},
  %{date_time: ~N[2018-05-12 03:02:00]},
  %{date_time: ~N[2018-05-12 03:02:00]},
  %{date_time: ~N[2018-05-12 03:02:00]},
  %{date_time: ~N[2018-05-12 03:02:00]},
  %{date_time: ~N[2018-05-12 03:02:00]},
  %{date_time: ~N[2018-05-12 03:02:00]},
  %{date_time: ~N[2018-05-12 03:02:00]}
]
kokolegorille

kokolegorille

There is no loop, it’s a list comprehension :slight_smile:

benwilson512

benwilson512

Author of Craft GraphQL APIs in Elixir with Absinthe

You risk promoting people doing:

result = foo()

If foo() succeeds then great, result has the result. If foo() fails however and returns an error then you have no idea.

Where Next?

Popular in Questions Top

Brian
What is the proper way to load a module from a file in to IEX? In the python world, doing something like this pretty standard: from ....
New
Tee
can someone please explain to me how Enum.reduce works with maps
New
LegitStack
I’m hoping you guys can give me some general advice and perhaps code examples if you’re feeling up to it. I’m very interested in Elixir,...
New
LegitStack
I’m trying to make a websocket server in Phoenix or raw Elixir. I heard about gun, I think I could use cowboy, but since I’m not that sma...
New
sabri
Can someone explain the settings of pool_size of Ecto in config file? and what is the recommend size? Thanks
New
Mooodi
Given a string, how can I get access to its character by index? Enum.at("my_string", 2) doesn't work. Or rather, not char, but a substr...
New
wernerlaude
In AR this is so simple @articles = current_user.articles How to do in Ecto? def index(conn, _params) do current_user = conn.assig...
New
jc00ke
Expanding on this topic: https://forum.elixirforum.net/t/map-typespec-question/19217 Let’s say I have a map with required and optional k...
New
jay1
Why is it that the mnesia database isn’t the most preferred database for use in Elixir/Phoenix?
New
joeerl
Hello again - after a longish gap I’ve decided I really must dig into Elixir and see what’s been happening here - so I have a few questio...
New

Other popular topics Top

JDanielMartinez
Hi! May someone helps me, please! I have two apps into an umbrella project: the first one is Database, which manages queries, and the se...
New
sorentwo
Hello! tl;dr Announcing Oban, an Ecto based job processing library with a focus on reliability and historical observability. After spen...
977 41022 311
New
openscript
Hello! Sorry for this astonishing simple question, but I’m really stuck. I try to set up the intellij-elixir plugin, but I don’t know ho...
New
AstonJ
You’re a programmer, so you don’t need spoon feeding with the conventional drivel about “this is an integer.” No. You need to know what’s...
New
chrismccord
This release brings a number of exciting features, including integration with the new Phoenix LiveDashboard and Phoenix LiveView. There h...
New
lk-geimfari
What is most correct way to open, read and parse JSON file with poison? For example if we have example.json file in root of some projec...
New
aadeshere1
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible. total = 10 while total != 0 ...
New
minhajuddin
I have seen a lot of code which picks the first element from a list using Enum.at(0) instead of List.first. Is there a reason why people ...
New
vonH
When I run the Plug and I recompile I wind up having to use Ctrl C to quit iex and start again. Witht the help of rlwrap I can use the cu...
New
ovidiubadita
Hey all, I discovered Elixir and I love it. I always wanted to learn a functional programming and I intended to go for Haskell, but afte...
New

We're in Beta

About us Mission Statement