Unformatted text preview:

548CS 538 Spring 2006©With function parameters, somefamiliar functions can be readilyprogrammed:class Map { static int[] map((int)->int f, int[] a){ int [] ans = new int[a.length]; for (int i=0;i<a.length;i++) ans[i]=f(a[i]); return ans; };}549CS 538 Spring 2006©And we can make such operationspolymorphic by using parametricpolymorphism:class Map<T> { private static T dummy; Map(T val) {dummy=val;}; static T[] map((T)->T f,T[] a){ T [] ans = (T[]) a.clone();for (int i=0;i<a.length;i++) ans[i]=f(a[i]); return ans; };}550CS 538 Spring 2006©Algebraic Data TypesPizza also provides “algebraic datatypes” which allow a type to bedefined as a number of cases. This isessentially the pattern-orientedapproach we saw in ML.A list is a good example of the utilityof algebraic data types. Lists come intwo forms, null and non-null, and wemust constantly ask which form oflist we currently have. With patterns,the need to consider both forms isenforced, leading to a more reliableprogramming style.In Pizza, patterns are modeled as“cases” and grafted onto the existingswitch statement (this formulation isa bit clumsy):551CS 538 Spring 2006©class List { case Nil; case Cons(char head, List tail); int length(){ switch(this){ case Nil: return 0; case Cons(char x, List t): return 1 + t.length(); } }}552CS 538 Spring 2006©And guess what! We can useparametric polymorphism along withalgebraic data types:class List<T> { case Nil; case Cons(T head, List<T> tail); int length(){ switch(this){ case Nil: return 0; case Cons(T x, List<T> t): return 1 + t.length(); } }}553CS 538 Spring 2006©Enumerations as AlgebraicData TypesWe can use algebraic data types toobtain a construct missing from Javaand Pizza—enumerations.We simply define an algebraic datatype whose constructors are notparameterized:class Color { case Red; case Blue; case Green; String toString() { switch(this) { case Red: return "red"; case Blue: return "blue"; case Green: return "green"; } }}554CS 538 Spring 2006©This approach is better than simplydefining enumeration values asconstant (final) integers:final int Red = 1;final int Blue = 2;final int Green = 3;With the algebraic data typeapproach,Red, Blue and Green, arenot integers. They are constructorsfor the typeColor. This leads to morethorough type checking.555CS 538 Spring 2006©PythonOne of the newest and mostinnovative scripting languages isPython, developed by Guido vanRossum in the mid-90s. Python isnamed after the BBC “Monty Python”television series.Python blends the expressive powerand flexibility of earlier scriptinglanguages with the power of object-oriented programming languages.It offers a lot to programmers:• An interactive development mode aswell as an executable “batch” modefor completed programs.• Very reasonable execution speed. LikeJava, Python programs are compiled.Also like Java, the compiled code is in556CS 538 Spring 2006©an intermediate language for whichan interpreter is written. Like Javathis insulates Python from many ofthe vagaries of the actual machineson which it runs, giving it portabilityof an equivalent level to that of Java.Unlike Java, Python retains theinteractivity for which interpretersare highly prized.• Python programs require nocompilation or linking. Nevertheless,the semi-compiled Python programstill runs much faster than itstraditionally interpreted rivals such asthe shells, awk and perl.• Python is freely available on almostall platforms and operating systems(Unix, Linux, Windows, MacOs, etc.)557CS 538 Spring 2006©• Python is completely object oriented.It comes with a full set of objectedoriented features.• Python presents a first class objectmodel with first class functions andmultiple inheritance. Also includedare classes, modules, exceptions andlate (run-time) binding.• Python allows a clean and openprogram layout. Python code is lesscluttered with the syntactic “noise”of declarations and scope definitions.Scope in a Python program is definedby the indentation of the code inquestion. Python thus breaks withcurrent language designs in thatwhite space has now once againacquired significance.558CS 538 Spring 2006©• Like Java, Python offers automatedmemory management through run-time reference counting and garbagecollection of unreferenced objects.• Python can be embedded in otherproducts and programs as a controllanguage.• Python’s interface is well exposed andis reasonably small and simple.• Python’s license is truly public.Python programs can be used or soldwithout copyright restrictions.• Python is extendable. You candynamically load compiled Python,Python source, or even dynamicallyload new machine (object) code toprovide new features and newfacilities.559CS 538 Spring 2006©• Python allows low-level access to itsinterpreter. It exposes its internalplumbing to a significant degree toallow programs to make use of theway the plumbing works.• Python has a rich set of externallibrary services available. Thisincludes, network services, a GUI API(based on tcl/Tk), Web support forthe generation of HTML and the CGIinterfaces, direct access to databases,etc.560CS 538 Spring 2006©Using PythonPython may be used in eitherinteractive or batch mode.In interactive mode you start up thePython interpreter and enterexecutable statements. Just naming avariable (a trivial expression)evaluates it and echoes its value.For example (>>> is the Pythoninteractive prompt):>>> 11>>>a=1>>> a1>>>b=2.5>>> b2.5561CS 538 Spring 2006©>>> a+b3.5>>>print a+b3.5You can also incorporate Pythonstatements into a file and executethem in batch mode. One way to dothis is to enter the commandpython file.pywhere file.py contains the Pythoncode you want executed. Be carefulthough; in batch mode you must useaprint (or some other outputstatement) to force output to beprinted. Thus1a=1a562CS 538 Spring 2006©b=2.5ba+bprint a+bwhen run in batch mode prints only3.5 (the output of the printstatement).You can also run Python programs asUnix shell scripts by adding the line#! /usr/bin/env pythonto the head of your Python file.(Since# begins Python comments,you can also feed the sameaugmented file directly to the Pythoninterpreter)563CS 538 Spring 2006©Python Command FormatIn Python, individual primitivecommands and expressions mustappear on a single line.This means that a =


View Full Document

UW-Madison COMPSCI 538 - Lecture 37 Notes

Download Lecture 37 Notes
Our administrator received your request to download this document. We will send you the file to your email shortly.
Loading Unlocking...
Login

Join to view Lecture 37 Notes and access 3M+ class-specific study document.

or
We will never post anything without your permission.
Don't have an account?
Sign Up

Join to view Lecture 37 Notes 2 2 and access 3M+ class-specific study document.

or

By creating an account you agree to our Privacy Policy and Terms Of Use

Already a member?