lilypond-user
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: test if an element occurs in a list exactly once


From: David Kastrup
Subject: Re: test if an element occurs in a list exactly once
Date: Thu, 28 Jun 2018 11:32:18 +0200
User-agent: Gnus/5.13 (Gnus v5.13) Emacs/27.0.50 (gnu/linux)

Urs Liska <address@hidden> writes:

> Hi,
>
> I have to validate symbol-lists in various ways. For example if it
> must contain exactly two values (in arbitrary order) I can do
>
>     (and (= (length mylist) 2)(memq 'val-a mylist) (memq 'val-b mylist))
>
> To test if only certain values are allowed (but may be there multiple
> times):
>
>     (every (lambda (elt) (memq elt '(val-a val-b))) mylist)
>
> Now I have a case where one value must be present once and another
> value at least once, so '(a b b) is valid as well as '(a b) but '(a a
> b) is invalid.
>
> I can use (filter) and check if the resulting list has exactly one
> element, but is there a "native" function to either check if an
> element is in a list exactly once?

If "in arbitrary order" is a general feature of your symbol list, there
are two obvious ways of preprocessing it depending on whether you are
doing bulk verification/processing or partial verification/processing
based on particular keys.

For bulk processing, you sort the list, then process it in linear order
once.  Multiple keys will occupy successive places then, not requiring
any search.

For key-based processing, you convert the list into a hash table, with
each symbol mapping to a count.  You can then look up each key in that
hash table and perform appropriate actions for its multiplicity.

-- 
David Kastrup



reply via email to

[Prev in Thread] Current Thread [Next in Thread]