lua-users home
lua-l archive

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


Here is a compact version (maybe not very efficient...)

  function lcp(lst, i, pfx)
      return (not lst[i] or lst[i]:sub(1, #pfx) == lcp(lst, i+1, pfx) )
              and pfx or lcp(lst, 1, pfx:sub(1, #pfx-1))
  end

aList = { 'foobarbaz', 'foobar', 'foo' }

> print( lcp(aList, 1, aList[1]) )
foo


Could be made nicer with one additional line:

  function lcp(lst, i, pfx)
      i = i or 1;  pfx = pfx or lst[1]
      return (not lst[i] or lst[i]:sub(1, #pfx) == lcp(lst, i+1, pfx) )
              and pfx or lcp(lst, 1, pfx:sub(1, #pfx-1))
  end

> print( lcp(aList) )
foo


Of course replacing the and/or with if/then/else would make it more
legible, but larger :-)

--Phil