[erlang-questions] List comprehension puzzler

Pagayon, Ruel <>
Tue Sep 20 17:14:51 CEST 2016


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


Thanks for clearing that up! That definitely is a better way.

Cheers,
Ruel

*Ruel Pagayon* - 
Platform Engineer
Networking and Communications

On Tue, Sep 20, 2016 at 11:00 PM, Raimo Niskanen <
> wrote:

> 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
> _______________________________________________
> erlang-questions mailing list
> 
> http://erlang.org/mailman/listinfo/erlang-questions
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20160920/e898503a/attachment.html>


More information about the erlang-questions mailing list