Double-exclamation mark syntax

Hi all. I was searching for ways to determine whether or not an Ecto query results in (a) result(s) without requiring the database to select columns as I don’t need the data and found this discussion in the Slack archive.

@michalmuskala shared this function which one can put in an app’s Repo module:

def exists?(query, opts \\ []) do
  query = from q in query, select: true, limit: 1
  case one(query, opts) do
    nil -> false
    true -> true
  end
end

An alternative to the case, which Paul Smith shared, which also gives true or false is:

!!one(query, opts)

I haven’t been able to find info on where the !! comes from and exactly what it does, so I thought I’d ask here. Is it a type coercion type of thing, and does anyone know where it’s documented? Apologies if this is just me utterly failing at using docs.

Thanks.

2 Likes

It enforces boolean value…

! is not

!! is not not, forcing true or false

3 Likes

Thanks. I’ve just tested !!!, and that seems to be not-not-not, so I suppose the reason that !! isn’t explicitly documented (unless I’ve just missed it) is that it’s simply applying additional negation. (By calling a function twice?)

1 Like

I think so…

Doing ! value gives You also boolean, but in the opposite order.

Right. !! isn’t a separate thing any more than not not true is. It’s just double application of a unary operator.

3 Likes