lua-users home
lua-l archive

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


On 01/11/2018 01:09 AM, Gavin Wraith wrote:
> [...]
> we have
>    tuple (1,2,3) == tuple (1, tuple (2,3)) --> true
> by definition but, alas,
>    tuple (1,2,3) == tuple (tuple (1,2), 3) --> false
> So are there any associative tupling functions?
> [...]> --
> Gavin Wraith (gavin@wra1th.plus.com)
> Home page: http://www.wra1th.plus.com/

Why not implement tuples via lists?

  tuple =
    function(...)
      local result = {type = 'tuple'}

      local process
      process =
        function(list)
          for i, el in ipairs(list) do
            if (type(el) == 'table') and (el.type == 'tuple') then
              process(el)
            else
              table.insert(result, el)
            end
          end
        end

      process({...})

      return result
    end

  is_equal =
    function(t_a, t_b)
      if (#t_a == #t_b) then
        for i = 1, #t_a do
          if (t_a[i] ~= t_b[i]) then
            return false
          end
        end
        return true
      else
        return false
      end
    end


  -- Verification:

  print(
    'true',
    is_equal(
      tuple(1, tuple(2, 3)),
      tuple(tuple(1, 2), 3)
    ),
    is_equal(
      tuple(1, tuple(2, 3)),
      tuple(1, 2, 3)
    ),
    is_equal(
      tuple(1, 2, 3),
      tuple(tuple(1, 2, 3))
    )
  )

  print(
    'false',
    is_equal(
      tuple(1, 2, 3),
      tuple(1, 2)
    ),
    is_equal(
      tuple(1, tuple(2, 3)),
      tuple(1, tuple(2))
    )
  )

-- Martin