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

Patoshizzle
After calling mix ecto.create I get this error: 17:00:32.162 [error] GenServer #PID&lt;0.412.0&gt; terminating ** (Postgrex.Error) FATAL...
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
joaquinalcerro
Hi there, I am working with Ecto-Postgresql and I need to call all of the records from a specific table but the table has 40,000 record...
New
tduccuong
Hi, is there any work on GUI with Elixir, that is similar to Electron/Javascript? My idea is to bundle Phoenix and BEAM into a single se...
New
vac
Hi, I'm quite new in Elixir and I'm trying to format a string to a PEM format. I have the certificate value like MIIDBTCCAe2...... and ...
New
alice
Hey, Just curious what are the main benefits of Elixir compared to Clojure? When is Elixir more useful than Clojure and vice versa? Th...
New
Fl4m3Ph03n1x
About me? ( if you have nothing better to do than reading about some random guy in the internet :stuck_out_tongue: ) Hello all, this is ...
New
Codball
Mix format works fine if run from the cmd. I’ve followed this to facilitate the implementation into VSC which involves downloading an ext...
New
skosch
To my knowledge, put_in, Map.update etc. all have the one limitation of not automatically creating intermediate keys when needed (for exa...
New
lucidguppy
I have a super simple question about elixir - how would I take a file like this foo bar baz and output a new file that enumerates th...
New

Other popular topics Top

TunkShif
This post is an instruction guide to help you setup your Neovim for Elixir development from scratch. It includes general information on h...
273 38985 115
New
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
William
I would like to know that is there any online source for learning Phoenix Framework for building E-Commerce Store? Any advantage on build...
New
ycv005
I have followed this StackOverflow post to install the specific version of Erlang. And When I am running mix ecto.setup then getting fol...
New
hariharasudhan94
I would like to know what is the best IDE for elixir development?
New
chrismccord
This release brings a number of exciting features, including integration with the new Phoenix LiveDashboard and Phoenix LiveView. There h...
New
polypush135
As many of you may have realized by now (sorry for all the posts here) I’ve been working on a db problem where I’m trying to aggregate a ...
New
myronmarston
The Elixir Typespec docs show the following syntax for keyword lists in typespecs: # ... | [key: type] # keyword lis...
New
danschultzer
None of the current solutions worked well for me, so I went ahead and built a user management system from scratch. This project took far...
548 27727 240
New
Nvim
Elixir appears to be a superior language to Python. I don’t see any advantage of Python over Elixir. Are there any?
New

We're in Beta

About us Mission Statement