[erlang-questions] illegal guard expression: filelib:is_dir(H)

Kay Kay kaykay.unique@REDACTED
Sun Feb 14 22:38:04 CET 2010



On 02/14/2010 03:01 AM, Kostis Sagonas wrote:
> Kay Kay wrote:
>> I have a function along the following lines
>>
>> do_process_elements([],  _) ->   [];
>> do_process_elements([H | _], Fn) ->
>>   if
>>     filelib:is_dir(H) ->
>>       process_directory(H, Fn);
>>     true ->
>>       process_file(H, Fn)
>>   end.
>>
>>
>> When I compile - I get the following error,  where the line number 
>> refers to    - filelib:is_dir(H) function.
>>
>> ./test.erl:23: illegal guard expression
>>
>> Given that filelib:is_dir(H) returns true / false  - I thought this 
>> would fit in here as a predicate. What could be going wrong ?
>
> The if construct in Erlang is very restrictive w.r.t. what it can be 
> used with.  Do not use it.  Use case instead:
>
>  do_process_elements([],  _) ->   [];
>  do_process_elements([H | _], Fn) ->
>    case filelib:is_dir(H) of
>      true ->
>        process_directory(H, Fn);
>      false ->
>        process_file(H, Fn)
>    end.
>
> Kostis

Thanks for the clarification.

 From a runtime cost - would this be any different ( in terms of 
time/space complexity) from adding another rule to do the same . (eg, as 
given below ? ) .


do_process_unixfile(true, H, Fn) ->
     process_directory(H, Fn);
do_process_unixfile(false, H, Fn) ->
     process_file(H, Fn).

  do_process_elements([],  _) ->   [];
  do_process_elements([H | _], Fn) ->
    do_process_unixfile( filelib:is_dir(H), H, Fn).

I find the latter 'purely' functional and amenable for optimization, 
than the former , which comes to me as a 'procedural' construct.  Is 
there any document / guide to refer to , for best practices with Erlang 
for cases like this ?




More information about the erlang-questions mailing list