What Is Func, How and When Is It Used

What is Func, how and when is it used

Func<T> is a predefined delegate type for a method that returns some value of the type T.

In other words, you can use this type to reference a method that returns some value of T. E.g.

public static string GetMessage() { return "Hello world"; }

may be referenced like this

Func<string> f = GetMessage;

Please what does func() mean in python when used inside a function

func is an argument given to the function identity_decorator().

The expression func() means "call the function assigned to the variable func."

The decorator is taking another function as an argument, and returning a new function (defined as wrapper) which executes the given function func when it is run.

Here is some information about decorators.

How do you use Func and Action when designing applications?

They're also handy for refactoring switch statements.

Take the following (albeit simple) example:

public void Move(int distance, Direction direction)
{
switch (direction)
{
case Direction.Up :
Position.Y += distance;
break;
case Direction.Down:
Position.Y -= distance;
break;
case Direction.Left:
Position.X -= distance;
break;
case Direction.Right:
Position.X += distance;
break;
}
}

With an Action delegate, you can refactor it as follows:

static Something()
{
_directionMap = new Dictionary<Direction, Action<Position, int>>
{
{ Direction.Up, (position, distance) => position.Y += distance },
{ Direction.Down, (position, distance) => position.Y -= distance },
{ Direction.Left, (position, distance) => position.X -= distance },
{ Direction.Right, (position, distance) => position.X += distance },
};
}

public void Move(int distance, Direction direction)
{
_directionMap[direction](this.Position, distance);
}

Func vs. Action vs. Predicate

The difference between Func and Action is simply whether you want the delegate to return a value (use Func) or not (use Action).

Func is probably most commonly used in LINQ - for example in projections:

 list.Select(x => x.SomeProperty)

or filtering:

 list.Where(x => x.SomeValue == someOtherValue)

or key selection:

 list.Join(otherList, x => x.FirstKey, y => y.SecondKey, ...)

Action is more commonly used for things like List<T>.ForEach: execute the given action for each item in the list. I use this less often than Func, although I do sometimes use the parameterless version for things like Control.BeginInvoke and Dispatcher.BeginInvoke.

Predicate is just a special cased Func<T, bool> really, introduced before all of the Func and most of the Action delegates came along. I suspect that if we'd already had Func and Action in their various guises, Predicate wouldn't have been introduced... although it does impart a certain meaning to the use of the delegate, whereas Func and Action are used for widely disparate purposes.

Predicate is mostly used in List<T> for methods like FindAll and RemoveAll.

Classes vs. Functions

Create a function. Functions do specific things, classes are specific things.

Classes often have methods, which are functions that are associated with a particular class, and do things associated with the thing that the class is - but if all you want is to do something, a function is all you need.

Essentially, a class is a way of grouping functions (as methods) and data (as properties) into a logical unit revolving around a certain kind of thing. If you don't need that grouping, there's no need to make a class.

What are function pointers used for, and how would I use them?

A simple case is like this: You have an array of operations (functions) according to your business logic. You have a hashing function that reduces an input problem to one of the business logic functions. A clean code would have an array of function pointers, and your program will deduce an index to that array from the input and call it.

Here is a sample code:

typedef void (*fn)(void) FNTYPE;
FNTYPE fn_arr[5];

fn_arr[0] = fun1; // fun1 is previously defined
fn_arr[1] = fun2;
...

void callMyFun(string inp) {
int idx = decideWhichFun(inp); // returns an int between 0 and 4
fn_arr[idx]();
}

But of course, callbacks are the most common usage. Sample code below:

void doLengthyOperation(string inp, void (*callback)(string status)) {
// do the lengthy task
callback("finished");
}

void fnAfterLengthyTask(string status) {
cout << status << endl;
}

int main() {
doLengthyOperation(someinput, fnAfterLengthyTask);
}

When a function is used in python, what objects need to be created?

In my tests, the fastest way to do what I needed to was to define all the constants I needed outside, then make the list of functions who need those constants outside, then pass the list of functions to the main function. I used dis.dis, cProfile.run, and timeit.timeit for my tests, but I can't find the benchmarking script and can't be bothered to rewrite it and put up the results.

What does - mean in Python function definitions?

It's a function annotation.

In more detail, Python 2.x has docstrings, which allow you to attach a metadata string to various types of object. This is amazingly handy, so Python 3 extends the feature by allowing you to attach metadata to functions describing their parameters and return values.

There's no preconceived use case, but the PEP suggests several. One very handy one is to allow you to annotate parameters with their expected types; it would then be easy to write a decorator that verifies the annotations or coerces the arguments to the right type. Another is to allow parameter-specific documentation instead of encoding it into the docstring.

Use a function before it is defined

You actually misunderstood it,
When you are using _FUNCTIONS = (_foo, _bar) , python expects _foo and _bar as a variable nothing fancy here, and since you haven't defined any reference to it yet, it's undefined, thus throws error.

In the second case, you're doing the same thing inside a function, by that time, the function is already available in python's scope, thus no error.

And as @khelwood has mentioned in the comment, the order does matter

PHP | What does 'use function function_name;' (where function is a PHP built-in function) do?

Ok is actually pretty easy, the main issue was, that I did not read properly the documentation or I just miss the part, is true though that the use keyword is widely used in PHP, besides with different functionality all together.
Either way, thanks for whom helped me figured out in the comment section[ (@riggsfolly, @peterm, @eis, @david) of the question and after good reading and testing I'd decided to post the answer my self.



Quick Answer

The use function [some_function] is a namespace which defines / import that function for a particular place, this place being the namespaced section givin possibility to have same named function from different namespace and even modifying the name with alias, both for functions and namespace all together.

It can be a user defined namespace, or the global namespace

In this case, calling built-in function this way merely for style / clarity but also may PHP Performance Tip: Use fully-qualified function calls when working with namespaces



Detailed Answer

So the usekeyword is scattered with these functionalities:

  • Namespace Import / Include: Modules (as packages), Classes, Traits, Interfaces, functions, constants
  • Use outer scope of variables in closure functions
  • Inject traits in Classes.

So my question refers to the first point Import / Include (Functions).

The namespace are somehow more evident when using Classes, as soon as a namespace is declared on the script, that script becomes relative to that namespace and not the global anymore. Hence, if you then call any classes that aren't defined in the very same script without specify the namespace, will result in error, example:

<?php    

namespace A\B\C;
class Exception extends \Exception
{
}

$a = new Exception('hi'); // $a is an object of class A\B\C\Exception
$b = new \Exception('hi'); // $b is an object of class Exception

$c = new ArrayObject; // fatal error, class A\B\C\ArrayObject not found

?>

But even more clear example is this:

<?php
namespace A\B\C;
$b = new Exception('hi'); // Uncaught Error: Class "A\B\C\Exception"

By removing the namespace, it goes back to the global context

<?php
$b = new Exception('hi'); // no errors..

However, this is not happening with the const and functions, that's why is little less obvious and will silently fall back to the outer scope if not found.

For functions and constants, PHP will fall back to global functions or constants if a namespaced function or constant does not exist.

<?php
namespace A\B\C;

const E_ERROR = 45;
function strlen($str)
{
return \strlen($str) - 1;
}

echo E_ERROR, "\n"; // prints "45"
echo INI_ALL, "\n"; // prints "7" - falls back to global INI_ALL

echo strlen('hi'), "\n"; // prints "1"
if (is_array('hi')) { // prints "is not array"
echo "is array\n";
} else {
echo "is not array\n";
}
?>

Finally, for some example regarding my question:
File functions.php
<?php

namespace MyApp\Package;

//use function var_dump;
function var_dump($var)
{
echo '[', __NAMESPACE__, '] don\'t wnat to do that...<br/>';
}
function explode($separator, $some_string)
{
echo '[', __NAMESPACE__, '] opps, bomb failed :(...<br/>';
}

File index.php

<?php

namespace MyApp;
require_once 'functions.php';

use MyApp\Package; // Demostrate that we can 'import' the entire package namespace
use function MyApp\Package\var_dump; // Import the function only

class A
{
public static function say() {
$a = "a";
$b = "b";
$data = ['a' => $a, 'b' => $b];
echo var_dump($data); // --> Calling the namespaced function
}
public static function sayReal()
{
$a = "a";
$b = "b";
$data = ['a' => $a, 'b' => $b];
echo \var_dump($data); // -> with \ we make the lookup fully-qualified and falls back to global
}
public static function explodeBadBomb($bomb="something to explode")
{
Package\explode(" ",$bomb); // -> demostrate that we can namespaced in withing blocks and statements
}
public static function explodeGooodBomb($bomb="something to explode")
{
echo print_r(\explode(" ", $bomb)); // again calling the built-in
}
}
A::say(); // [MyApp\Package] don't wnat to do that...
A::sayReal(); // array(2) { ["a"]=> string(1) "a" ["b"]=> string(1) "b" }
A::explodeBadBomb(); // MyApp\Package] opps, bomb failed :(...
A::explodeGooodBomb(); // Array ( [0] => something [1] => to [2] => explode )

Documentation

  • Using namespaces: fallback to global function/constant
  • Namespaces
  • FAQ: things you need to know about namespaces

More on performance improvement

  • PHP RFC: declare(function_and_const_lookup='global')
  • [RFC] "use global functions/consts" statement

Related StackOverflow Questions / Answers

  • Should a PHP interface have a namespace?
  • How and where should I use the keyword "use" in php
  • In PHP, what is a closure and why does it use the "use" identifier?
  • Use keyword in functions - PHP


Related Topics



Leave a reply



Submit