Function Returning Unchanged Parameter in Lua

functionsluamethod-chainingparameters

I just found this function in the project I'm working at:

  -- Just returns the text unchanged.
  -- Note: <text> may be nil, function must return nil in that case!
  function Widget:wtr(text)
      return text
  end

Too sad, the coder does not work in the company anymore. Why would one make a function that does nothing, but returns the parameter it's called with?

Is there any use to such a function, not specified to this example, but overall in any case?

Due to

function aFunction(parameter)
    return parameter
end

Ends in

aFunction(parameter) == parameter

Why would I write something like

aFunction(parameter) == whatIWantToCheck

instead of

parameter == whatIWantToCheck

?

Best Answer

Your question is sort of like asking what's the good of the number zero if whenever you add it to something you get the same value back. An identity function is like the zero for functions. Kind of useless by itself, but occasionally useful as part of an expression using higher-order functions, where you can take a function as a parameter or return it as a result. That's why most functional programming languages have an id or identity in their standard library.

Put another way, it makes a handy default function. Just like you might want to set offset = 0 as a default integer, even though that makes an offset do nothing, it might come in handy to be able to set filterFunction = identity as a default function, even though that makes the filter do nothing.

Related Topic