[erlang-questions] List comprehension puzzler

Raimo Niskanen <>
Tue Sep 20 17:00:18 CEST 2016


On Tue, Sep 20, 2016 at 10:17:36PM +0800, Pagayon, Ruel wrote:
> Hello Lloyd,
> 
> One thing to help optimise your code: Guards
> 
> isbn_format_valid(ISBN) when length(ISBN) == 10 orelse length(ISBN) == 13 ->
>   [I || I <- ISBN, I < $0 orelse I > $9] == [];
> 
> isbn_format_valid(_ISBN) ->
>   false.
> 
> 
> This makes your "is the number equal or between 0 and 9" only be executed
> if the length is 10 or 13. Reason for this, is if user inputs a very large
> list, you won't have to compare every character only to find later that
> it's not the right length (your machine will take the toll).

Note that length(ISBN) will be called twice on this maybe very long list,
and that in itself may be bad since length/1 is O(N).

See my do-it-with-plain-functions safer but more verbose example.

-- 

/ Raimo Niskanen, Erlang/OTP, Ericsson AB


More information about the erlang-questions mailing list