PythonPP + lambda: example, pythonpplam.pdf
Directly add the code. Download python PP. You can download Python PP from the official website.
What lambda can do is basically be done by common functions. Lambda is mainly used to simplify expressions and seems to be particularly suitable for expressing scientific formulas. Combined with functions such as map and reduce, you can obtain more powerful and "elegant" expression capabilities. The "Elegance" here does not necessarily mean comprehension, but it is often because a short and refined code makes people shine.
The following code demonstrates lambda usage and python concurrent programming.
import ppfrom multiprocessing import Process, Pool, Pipedef addNFunc(n): return lambda x:x+ndef fac(n): if n <= 1: return 1 return reduce(lambda x,y: x*y, map(addNFunc(1), range(n)))def computingFacOfRange(begin, end): for i in map(addNFunc(begin), range(end-begin+1)): print i, '! =', fac(i)def another(): print 'another quick job' def QuadraticSum(n, m): ''' compute 1^m + 2^m + ... + n^m ''' if n <= 1: return 1 return reduce(lambda x,y: x+y**m, map(addNFunc(1), range(n)))def expressQS(n,m): if n <= 1: return '1' return reduce(lambda x,y: "%s+%s" %(str(x),str(y)+'^'+str(m)), map(addNFunc(1), range(n)))def obtainQuadraticSum(n, m): return "%s=%s" % (expressQS(n, m), QuadraticSum(n,m))def obtainQuadraticSumByPipe(conn, n, m): conn.send(obtainQuadraticSum(n, m))def printQuadraticSum(n, m): print obtainQuadraticSum(n, m)def testQuadraticSum(): for n in [1,2,3,4,5]: for m in [-1,1,2,3]: printQuadraticSum(n, m) def usingPP(): ''' using pp module for python concurrent programming ''' nworkers = 10 ppservers = () job_server = pp.Server(nworkers, ppservers=ppservers) print "Starting pp with", job_server.get_ncpus(), "workers" jobs = [] for i in range(nworkers): jobs.append(job_server.submit(computingFacOfRange, (i*10+1, (i+1)*10), (fac,addNFunc,))) jobs.append(job_server.submit(another, ())) for job in jobs: job() job_server.print_stats() def usingMultiprocess(): ''' using multiprocessing module for python concurrent programming ''' num = 100 processes = [] print '************ using original process ***********' input_conn, output_conn = Pipe() for m in [-1,1,2,3]: p = Process(target=obtainQuadraticSumByPipe, args=(input_conn, num,m,)) p.start() print output_conn.recv() print '------------- using Pool -------------' pool = Pool(processes=4) for m in [-1,1,2,3]: pool.apply(printQuadraticSum, (num,m)) if __name__ == '__main__': testQuadraticSum() usingPP() usingMultiprocess()
Net lambda Expression Tree
There is a class named Dynamic. cs, which is open-source by Microsoft. You can search it online. Its running example is as follows:
Var query = db. MERs. where ("City = @ 0 and Orders. count> = @ 1 "," London ", 10 ). orderBy ("CompanyName "). select ("New (CompanyName as Name, Phone )");
How to Use Lambda expressions for abstract representation
However, it also has some shortcomings. If a method parameter contains an abstract type such as System. Delegate, use a lambda expression to introduce a special problem: the C # compiler cannot convert a lambda expression to a derivative representative type that has not yet been clearly defined. Without careful consideration, your code looks like something from. NET1.0. In this article, I will tell you why lambda expressions are insufficient to be directly converted to abstract representative types, and teach you how to make the compiler convert the specified representatives you define. The solution depends on the Windows Presentation Foundation (WPF) and System. Windows. Threading. Dispatcher components, but strictly speaking, this issue is not a WPF issue. The problems described in this article appear in several. NET frameworks, including Windows Forms, Office application interfaces, and ing application interfaces. You can solve similar problems in the following ways. Whenever I use an application interface with parameters representing tables in the. NET Framework, I tend to use lambda expressions instead of more detailed expressions. For example, this line of code creates a System. windows. threading. timer, when the Timer fails, the Code calls a TickHandler method: tick = new System. threading. timer (unused) => TickHandler (); If the content of the method is small enough, I will replace the TickHandler () method call with the content of the method. This method works in most cases, but this technique does not work when the application interface uses System. Delegate as a parameter. For example. windows. controls. dispatcher. the Invoke () method is called through a thread in WPF: public object Invoke (delegate method, params object [] args). Now, when we try to use a lambda expression to execute such a call, what will happen: MyTime. dispatcher. invoke () => DoSomething (); a hidden error occurs: error CS1660: Cannot convert lambda expression totype' System. delegate 'because it is not a delegate type. Maybe the first time you see this error, you still don't know what it is. Of course, this is indeed a representative type. Compilers are not as flexible as humans. The System. Delegate type is an abstract type. Reasoning tools of this type cannot infer the number and type of values returned by a derived variable or an unknown representative type. To solve this problem, we must create a specific representative type and specify a lambda expression for this type. Remember, the Representative type requires you to regard the method as data. I created a WPF Timer Program to demonstrate how it works. It explains how C #3.0 simplifies the running of interfaces with older applications. When you do the demo, the app in this example runs a timer. As the set time passes, the color of the timer changes from green to yellow and then red. This is a good way to demonstrate cross-thread calling, because the timer runs in the background thread. Update the demo Based on Time changes to respond to events from the timer. The timer runs in the background thread, so you will easily make the mistake we mentioned earlier. The updated application user interface processes simple code. It takes effect when the timer expires, and the code updates the timer display. This update must change the text or control the background. As shown in the following figure: MyTime. Background = newBrush; MyTime. Content = label timing ...... the remaining full text>