identity
identity(x)
The identity function. Returns its argument.
Examples
In the Julia programming language, the identity function simply returns its argument.
julia> identity(5)
5
julia> identity("Hello")
"Hello"
Here are some common examples of using the identity function:
-
Passing a variable through unchanged:
julia> x = 10; julia> identity(x) 10It returns the value of
xunchanged. -
Using
identityin a function composition:julia> f(x) = x^2; julia> g(x) = x + 1; julia> h = f ∘ g ∘ identity; julia> h(5) 36Here,
identityis used in a function composition to pass the intermediate result through unchanged. - Applying
identityto arrays:julia> arr = [1, 2, 3, 4]; julia> result = map(identity, arr); julia> result 4-element Array{Int64,1}: 1 2 3 4It can be used with
mapto create a new array with the same elements.
Common mistake example:
julia> identity(1, 2)
ERROR: MethodError: no method matching identity(::Int64, ::Int64)
In this example, the identity function is called with two arguments, but it only accepts a single argument. Make sure to provide only one argument to the identity function.
See Also
User Contributed Notes
Add a Note
The format of note supported is markdown, use triple backtick to start and end a code block.