Domanda

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

È stato utile?

Soluzione

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,

Altri suggerimenti

The illegal guard statement comes from calling the ets:first(Cal) function from within an if statement guard. so if ets:first(Cal) =/= '$end_of_table' -> is not going to compile correctly. Guard statements only have a small set of functions that can be used, read about them here.

Also if statements are a little different in Erlang vs. other languages. One clause at least must evaluate to true. The Documentation on if statements explains this behavior, and how an error is thrown if no clause evaluates to true.

So moving the ets:first(Cal) outside of the if statement and adding a catch all true case to your code, should work:

Res = ets:first(Cal),
if 
  Res =/= '$end_of_table' ->
    Event = ets:first(Cal),
    {TimeAtStart, Ref} = Event,
    NowTime = now(),
    Ms = timer:now_diff(NowTime, TimeAtStart)div 1000;
  true -> ok %% you need a default clause
end,

However, if it was me doing my school project, I would try to use the ets:info function to check the size of the table, and do it inside of a case statement. Checkout the Documentation on the ets:info function, and the case statement.

Just FYI: I don't think I have used an if statement the entire time I have been programming in Erlang.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top