Search code examples
erlangets

How to use an if-structure for finding out if ets table is empty


I am new to Erlang. I have a project for school which uses an ets:table. But before I want to get some data out of the ets:table, I want to use an if-structure for checking out the table if it isn't empty.

 if 
   ets:first(Cal) =/= '$end_of_table' ->
     Event = ets:first(Cal),
     {TimeAtStart, Ref} = Event,
     NowTime = now(),
     Ms = timer:now_diff(NowTime, TimeAtStart)div 1000
   end,

Now this gives me an error: Illegal guard expression.

I don't know what I'm doing wrong, please help.

With friendly regards

Daan


Solution

  • if expect a guard sequence. so it fails. You could make the test before the if, and use the result, but with your code, when you get '$end_of_table', it will fails also since you have not true statement.

    I recommend to use a case statement for your code:

    case ets:first(Cal)  of
         '$end_of_table' ->
               {error,no_entry};
         {TimeAtStart, _Ref} ->
               {ok,timer:now_diff(now(), TimeAtStart)div 1000}
    end,