Unisay / purescript-lua

Purescript compiler back-end for Lua
GNU General Public License v3.0
56 stars 2 forks source link

Optimize pattern matching on product types #6

Closed Unisay closed 1 year ago

Unisay commented 1 year ago

Product types, e.g. Tuples are compiled to the following code atm:

data Tuple = T Int Int

fst :: Tuple -> Int
fst (T x _) = x
  T = function(value0)
    return function(value1)
      return { ["$ctor"] = "Tuple.T", value0 = value0, value1 = value1 }
    end
  end,
  fst = function(v)
    if "Tuple.T" == v["$ctor"] then
      return v.value0
    else
      return error("No patterns matched")
    end
  end

the runtime ctor check isn't needed in case of product types as they always have at most one constructor:

  T = function(value0)
    return function(value1)
      return { ["$ctor"] = "Tuple.T", value0 = value0, value1 = value1 }
    end
  end,
  fst = function(v) return v.value0 end