boriscy

boriscy

Try this

Decimal.new(-1) > Decimal.new(0) # true
Decimal.new(-1) < Decimal.new(0) # false

Is this the correct way, I’m using Decimal.compare/2 to work but I would like an explanation

Showing Posts 1 to 10

NobbZ

NobbZ

I tried, didn’t work. Could you please elaborate which library you are using?

iex(1)> Decimal.new(-1)
** (UndefinedFunctionError) function Decimal.new/1 is undefined (module Decimal is not available)
    Decimal.new(-1)
peerreynders

peerreynders

My assumption would be that Decimal.new/1 returns an instance of it’s datatype. Meanwhile Kernel.>/2 simply compares this datatype based on some default rules - i.e. it has no idea what the actual number/value of a Decimal datatype is. So Decimal.compare/2 is the correct way of comparing two Decimals (i.e. don’t think of them as “numbers”).

Looking at the source: decimal.ex line 714

def new(int) when is_integer(int),
    do: %Decimal{sign: (if int < 0, do: -1, else: 1), coef: Kernel.abs(int)}

decimal.ex line 1

defmodule Decimal do
...
  defstruct [sign: 1, coef: 0, exp: 0]

Structs - Elixir

Structs are bare maps underneath

So Kernel.>/2 is comparing two maps - not two decimal values.

boriscy

boriscy OP

I’m in a phoenix project

defp deps do
    [{:phoenix, "~> 1.2.0-rc.0"},
     {:postgrex, ">= 0.11.1"},
     {:phoenix_pubsub, "~> 1.0.0-rc"},
     {:phoenix_ecto, "~> 3.0-rc.0"},
     {:phoenix_html, "~> 2.5.1"},
     {:phoenix_live_reload, "~> 1.0", only: :dev},
     {:gettext, "~> 0.11"},
     {:cowboy, "~> 1.0"},
     {:poison, "~> 2.1", override: true}, #{:poison, "~> 1.5"},
     {:comeonin, "~> 2.4.0"},
     {:guardian, "~> 0.10.1"},
     {:credo, "~> 0.3", only: [:dev, :test]},
     {:ex_machina, "~> 1.0.0-beta.1", github: "thoughtbot/ex_machina", only: :test}
   ]
  end
peerreynders

peerreynders

NobbZ

NobbZ

Then the module Decimal is propably from package decimal, which is a dependenciy of opostgrex and phoenix_ecto.

And in fact, the new/1 function of that module is returning a struct, which again are implemented using erlang maps.

Erlang does describe the comparison of a map like this:

link

So after we already know the definition of Decimal.new/1 is def new(int) when is_integer(int), do: %Decimal{sign: (if int < 0, do: -1, else: 1), coef: Kernel.abs(int)}, we can also tell that we will get the following maps back:

  • Decimal.new(-1) #=> %{__struct__: Decimal, sign: -1, coef: 1, exp: 0}
  • Decimal.new(0) #=> %{__struct__: Decimal, sign: 0, coef: 0, exp: 0}

Now comparing them:

  1. Ordered by size: They have the same size
  2. Ordered by keys: the keys are the same
  3. Ordered by values (comapred in order [:__struct__, :coef, :exp, :sign])
  4. __struct__: equal!
  5. :coef: Comparing 1 and 0, BEAM comes to the conclusion that 1 is greater than 0 and will return an appropriate answer to your question.
  6. It does not care anymore for :exp and :sign
Qqwy

Qqwy

TypeCheck Core Team

Your assumption is correct.

The Decimal library that is used by Ecto (see it for yourself using mix deps.tree) represents decimals as Structs.

Internally, structs are represented as maps. The comparison operators work, for historical reasons, for all basic datatypes. (Even comparing different datatypes with each other is supported, i.e. comparing a number to a list or a tuple to a map. For the curious: number < atom < reference < fun < port < pid < tuple < map < list < bit string)

This is an (arguably ugly) implementation detail of Erlang. Code we write using a data type from some library should not care about the internal structure of that data type, i.e. we should treat it as a ‘black box’ (this improves code decoupling).

However, as a Decimal is supposed to be a number, it would be nice to compare it to all other kinds of numbers. But here another (arguably ugly) internal implementation detail of Erlang comes up: Operators like > are allowed inside Guard clauses, but only since they are on a very small white-list of ‘guard-safe built-in functions’. When we redefine >, this is no longer possible.

This is the reason that libraries like Decimal and Timex use functions like *.compare/2 instead of > and < for comparisons. I really hope that this will change in the future (for instance, if Erlang introduces guard-safe short-circuiting boolean-logic operators we could build many custom guard-safe operators), as it feels very Java-esque to me.

Tl;Dr: For the time being, you’ll have to use *.compare/2 to compare custom data types.

boriscy

boriscy OP

Wow thanks a lot you really care!! :heart_eyes:

Qqwy

Qqwy

TypeCheck Core Team

@Nobbz Interesting! This would suggest that if we reorder the Struct fields in Decimal, we could make the comparison operators work:

defmodule EpicDecimal do
   defstruct "1sign": 0, "2exp": 0, "3coef": 0
end

x = %EpicDecimal{"3coef": 0}
y = %EpicDecimal{"3coef": 3}
z = %EpicDecimal{"3coef": 3, "1sign": -1}
z < x && x < y

But this is probably a horrible idea for some other reasons ^^'. (one thing I can think of is, because the sign is separate, that -0 < 0, which should be equal)

NobbZ

NobbZ

If you are comparing Decimals to Decimals that would really work yes, but Decimal.new(1) < 0 would still return false, since integer is always greater than a map…

peerreynders

peerreynders

It took me a bit by surprise that Decimal.compare/2 returns Decimal<-1>, Decimal<0>, or Decimal<1>. I guess it makes sense that you want to stay within the same domain and you view compare as sgn(a - b) (Sign function). However coming from other languages one might be primed to expect integer -1, 0, or 1.

Using Decimal.cmp/2 returning :lt, :eq, or :gt may actually be clearer.

Where Next? Top

Trending in Questions Top

RSP87
I’m working on a project that simulates the bumbl example in the programming phoenix book. It acts almost like an email client. We have a...
New
nseaSeb
Hello, I know there is an approach for handling lists that allows for optimized traversal, but I can’t recall the specific method (somet...
New
brecabral
Documentation While reading the Scoped Routes section, I noticed that the documentation currently refers to a problem without explainin...
New
RemyXRenard
I’m seeing that a list inside a Kino.DataTable will be interpreted as a charlist, even if the Kino.configure() is set to charlists: :as_l...
New
velrest
So my question is quite simple and i have found no conclusive answer on forum, google or AI. Should we use :erlang.float for Integer to ...
New
asweet-confluent
I recently noticed that Elixir’s Logger defaults its primary log level to :debug when no :logger, :level application configuration is pre...
New
samoloth
Hi, I’ve just set up an application with ash_authentication. There is only magic link strategy for now, so there is no confirmation add o...
New

Other Trending Topics Top

JesseHerrick
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
New
mudasobwa
I am happy to introduce the very α version of the new programming language compiled to BEAM. Welcome Cure. It has literally three kille...
New
marciok
Hi there! We created Gust: A task orchestrator inspired by Airflow. For those who have never heard about Aiflow, it’s a Python-based wor...
New
mhanberg
Hi everyone! The first release candidate for the Expert language server project is now available! We’ve published a press release detai...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
Dmk
Xamal is a deployment tool for Elixir apps that deploys native releases to bare metal servers over SSH. It’s a port of GitHub - basecamp/...
New

Latest on Elixir Forum

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews