MatijaL

MatijaL

Hello,

I created a function which takes timedate as parameter in NaiveDateTime format. This date is an end date and the function has to calculate how much time is left from now to this end date.

def time_remaining(ends_at) when not is_nil(ends_at) do
    days_remaining = NaiveDateTime.diff(ends_at, NaiveDateTime.utc_now(), :day)

    if days_remaining < 1 do
      difference = NaiveDateTime.diff(ends_at, NaiveDateTime.utc_now(), :second)
      hours = div(difference, 3600)
      minutes = div(difference, 60) - (hours * 60)
      seconds = rem(difference, 60)

      "#{hours}h : #{minutes}min : #{seconds}s Remaining"
    else
      "#{days_remaining} Days Remaining"
    end
  end

The functions works as expected but VSCode is giving me this warning:

Guard test 
          _@46 ::
              {'safe',
               binary() |
               maybe_improper_list(binary() |
                                   maybe_improper_list(any(),
                                                       binary() | []) |
                                   byte(),
                                   binary() | [])} =:= 
          'nil' can never succeed

Can someone please help me locate the problem?

Showing Posts 1 to 10

kartheek

kartheek

Do you have another function which pattern matches for nil ?

def time_remaining(nil), do: # do something 

if you don’t have it may be you can rewrite it this way to handle nil:

def time_remaining(nil),  do: # do something return an error or empty string 
def time_remaining(ends_at) do
    days_remaining = NaiveDateTime.diff(ends_at, NaiveDateTime.utc_now(), :day)

    if days_remaining < 1 do
      difference = NaiveDateTime.diff(ends_at, NaiveDateTime.utc_now(), :second)
      hours = div(difference, 3600)
      minutes = div(difference, 60) - (hours * 60)
      seconds = rem(difference, 60)

      "#{hours}h : #{minutes}min : #{seconds}s Remaining"
    else
      "#{days_remaining} Days Remaining"
    end
  end
MatijaL

MatijaL OP

Thanks for checking it out, unfortunately, nil handling doesn’t help, the warning remains.

kartheek

kartheek

What happens when you invoke function time_remaining with nil ?

sodapopcan

sodapopcan

What version of Elixir are you using? I get no warnings when I compile in 1.14.1.

Regardless, since ends_at must be a NaiveDateTime, it’s better to be explicit about this in the function head as opposed to just checking that it isn’t nil:

def time_remaining(%NaiveDateTime{} = ends_at) do
  ...
end

or if you prefer when you can do the more verbose:

def time_remaining(ends_at) when is_struct(ends_at, NaiveDateTime) do
  ...
end
Sebb

Sebb

Sure that is coming from this function?
Would expect sth like ends_at@... here.

sbuttgereit

sbuttgereit

I haven’t seen this type of Dialyzer warning on a guard call before; but I have seen similar warnings for function parameters when Dialyzer thinks there’s no way for a given pattern match to possibly match a condition… which I sometimes do for a catch all function.

For example if I write something like the below, with no other calls to func_a/1:

def entry_func() do
  %{test: "Hi!"}
  |> func_a()
end

def func_a(%{} = param) do
  # do something
end

def func_a(_) do
  raise "Bad Param"
end

I will, with some regularity, see the ElixirLS Dialyzer warning that the second function head for func_a will never run… which looks like it could be similar to what you’re seeing. In this case Dialyzer isn’t exactly wrong… there’s no way for the second func_a/1 function head to match. But it’s not exactly helpful either because I may know now that in the future I might call it from somewhere else where the second function head is helpful.

Anyway, I can’t say for sure this is what you’re seeing, but it looks similar.

al2o3cr

al2o3cr

I don’t think the error is in the time_remaining function shown; the success typing in the error message doesn’t match anything that would appear inside that function.

It’s instead a synonym for Phoenix.HTML.safe. Maybe there’s a when not is_nil check someplace in the template near where this is used?

MatijaL

MatijaL OP

@Sebb
Sure that is coming from this function?
Would expect sth like ends_at@... here.

@al2o3cr
I don’t think the error is in the time_remaining function shown; the success typing in the error message doesn’t match anything that would appear inside that function.

Yes, it looks like something else is happening here… if I remove the logic from this function and make it to return just a simple string, VSCode still shows the same error but starts highlighting the code in another function so the error is probably somewhere else,=. I will isolate each function from that view and and try to find the problem that way. Thanks for your help.

Sebb

Sebb

yes, @al2o3cr is right, didn’t look that closely.

You can try to delete the .elixir-ls folder and restart/reload vscode.
Sometimes there is a hickup.
And maybe install dilyxir and run mix dialyzer to get a better picture.

MatijaL

MatijaL OP

Deleting .elixir_ls folder solved it, thanks for taking the time to help me out here.

— All posts loaded —

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
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
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

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