Function Composition Practice

Function Composition

You have already defined functions, passed parameters, returned values, and practiced safe variable scope. In this lesson, we will combine those skills to design a small, clear workflow using multiple functions. Think of this as a reminder of earlier ideas, but now applied together: small, focused functions that compose into a complete solution.

Build Small Helpers: sum_prices and apply_discount

Lua
local function sum_prices(prices)
    local total = 0
    for _, price in ipairs(prices) do
        total = total + price
    end
    return total
end

Explanation: This helper function iterates through a list of item prices with ipairs, adds them up into total, and returns the sum. Using local keeps the function and its variables scoped and safe.

Lua
local function apply_discount(total, discount)
    return total - discount
end

Explanation: This function does one thing: subtract a discount from a total and return the result. Clear inputs, clear output, no side effects.

Compose Functions: final_price

Lua
local function final_price(prices, discount)
    local total = sum_prices(prices)
    return apply_discount(total, discount)
end

Explanation: Here, you see function composition in action. We first compute the total using sum_prices, then pass that result into apply_discount. This keeps each function simple, while the combination solves a larger task.

Run the Plan

Lua
local item_prices = {100, 200, 50}
local discount = 30

local price = final_price(item_prices, discount)
print("The final price is: $" .. price)  -- Output: The final price is: $320

Explanation: We define our inputs as local values, call final_price to run the whole workflow, and print the result using string concatenation. The output shows that 100 + 200 + 50 = 350, and 350 - 30 = 320.

Summary and Next Steps

You combined small, focused functions into a clean pipeline:

  • sum_prices totals a list.
  • apply_discount adjusts the total.
  • final_price composes both to produce the answer.

This is how you build bigger programs — by composing small parts. Head to the practice section to apply these ideas and strengthen your ability to design modular Lua code.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal