In mathematics, an identity function is a function that returns the arguments that are passed to it unchanged. While the concept of an identity function is quite often useful in formulating proofs, it is not something that I ever expected to use in a programming environment. Here’s the identity function written in PowerShell:
function identity{ return $args }
The surprising thing about this function is that it’s actually pretty useful. PowerShell’s array literal syntax is considerably more involved than it’s argument syntax. Using this function lets us do this:
identity arg1 arg2 arg3
instead of this:
@('arg1','arg2','arg3')
That is cool. Didn’t know that was the identity function. I came across this from Bruce Payette and Jeffrery Snover and use it like this all the time:
function ql {$args}
$list = ql tom dick harry
Also, isn’t this also the identity function in PowerShell?
{param($x) $x}
Then you can apply the identity function to the identity function:
& {param($x) $x} {param($x) $x}
Good stuff
When I first tried to recreate this (I dimly remembered seeing it somewhere, and I really wanted to avoid quoting all the items in a large list), I tried something like your suggestion.
Unfortunately, by specifying an argument ($x), you’ve lost all of the magic. This will bind $x to the first item in the list, and the rest get bound to $args. If you pass “a b c” as to your scriptblock, you only get “a” back. The usefulness in this comes from getting the list of arguments back as an array.
Thanks for the comment.