Command that gives index of element in list

Discussion in 'Cadence' started by Alan Rodricks, Aug 24, 2005.

  1. Hi

    Is there a command that will give me the index of an element in a

    Alan Rodricks
    Alan Rodricks, Aug 24, 2005
  2. Alan Rodricks

    tattvamasi Guest

    One of the possible solutions would be to convert that to an array and
    then get the element with the given index

    something like this,

    a = list( 1 2 3)

    tattvamasi, Aug 25, 2005
  3. Alan Rodricks

    S. Badel Guest

    a = list( 1 2 3)
    easier would be to use nth(0 a) however i think the question was about the opposite.
    i'll assume that.
    i'm not aware of such a function, however it's rather easy to write one

    procedure( indexof(x lst)
    length(lst) - length(member(x lst))

    since member returns the tail of the list starting at the given element.

    S. Badel, Aug 25, 2005
  4. Alan Rodricks

    Trevor Bowen Guest

    I don't think there is a command to do this directly, so I always do this:

    ;; define procedure
    procedure(getElemIndex(elem list)
    when(foundList = member(elem list)
    ) ; ** when foundList **

    ;; test and examine usage
    a = list(1 2 3 4 5 6 7 8 9 1 2 3 4 5)

    getElemIndex(1 a) => 0
    getElemIndex(9 a) => 8
    getElemIndex(10 a) => nil

    Obviously, it only reports the index of the first match.



    Trevor Bowen, Aug 25, 2005
  5. More efficient would be:

    procedure(ABgetIndex(elem list)
    let(((count 0))
    exists(val list val==elem || count++ && nil) && count

    This only has to traverse the list for as many items as don't match. Yours would
    traverse the whole list twice in total. Mine would therefore take on average
    1/4 of the list hops that yours would.

    However, one thing to ask is why would you want to do this? Finding the index of
    an entry in a list suggests that it is being treated as an array - when it is a
    sequential structure. In other words, once you've found the index, what are you
    going to do with it? If you're going to then use nth() etc to locate the element
    later, that's not a good approach.

    There may be a perfectly good usage for this, but you may well be approaching
    the real problem the wrong way?



    Andrew Beckett, Aug 27, 2005
Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.