Slides from INF3330 lectures Hans Petter Langtangen About this course Dept. of Informatics, Univ. of Oslo & Simula Research Laboratory August 2007 � www.simula.no/˜hpl c Slides from INF3330 lectures – p. 1 About this course – p. 2 What is a script? Characteristics of a script Very high-level, often short, program Glue other programs together written in a high-level scripting language Extensive text processing Scripting languages: Unix shells, Tcl, Perl, Python, File and directory manipulation Ruby, Scheme, Rexx, JavaScript, VisualBasic, ... Often special-purpose code This course: Python Many small interacting scripts may yield a big system + a taste of Perl and Bash (Unix shell) Perhaps a special-purpose GUI on top Portable across Unix, Windows, Mac Interpreted program (no compilation+linking) � www.simula.no/˜hpl c � www.simula.no/˜hpl c About this course – p. 3 About this course – p. 4 Why not stick to Java or C/C++? Scripts yield short code (1) Features of Perl and Python compared with Java, C/C++ Consider reading real numbers from a file, where each and Fortran: line can contain an arbitrary number of real numbers: 1.1 9 5.2 shorter, more high-level programs 1.762543E-02 0 0.01 0.001 much faster software development 9 3 7 more convenient programming Python solution: you feel more productive F = open(filename, ’r’) Two main reasons: n = F.read().split() no variable declarations, but lots of consistency checks at run time lots of standardized libraries and tools � www.simula.no/˜hpl � www.simula.no/˜hpl c c About this course – p. 5 About this course – p. 6 Scripts yield short code (2) Using regular expressions (1) Perl solution: Suppose we want to read complex numbers written as text open F, $filename; $s = join "", <F>; (-3, 1.4) or (-1.437625E-9, 7.11) or ( 4, 2 ) @n = split ’ ’, $s; Python solution: Doing this in C++ or Java requires at least a loop, and in m = re.search(r’\(\s*([^,]+)\s*,\s*([^,]+)\s*\)’, Fortran and C quite some code lines are necessary ’(-3,1.4)’) re, im = [float(x) for x in m.groups()] Perl solution: $s="(-3, 1.4)"; ($re,$im)= $s=~ /\(\s*([^,]+)\s*,\s*([^,]+)\s*\)/; � www.simula.no/˜hpl c � www.simula.no/˜hpl c About this course – p. 7 About this course – p. 8
Using regular expressions (2) Script variables are not declared Regular expressions like Example of a Python function: \(\s*([^,]+)\s*,\s*([^,]+)\s*\) def debug(leading_text, variable): if os.environ.get(’MYDEBUG’, ’0’) == ’1’: constitute a powerful language for specifying text print leading_text, variable patterns Dumps any printable variable Doing the same thing, without regular expressions, in (number, list, hash, heterogeneous structure) Fortran and C requires quite some low-level code at the Printing can be turned on/off by setting the environment character array level variable MYDEBUG Remark: we could read pairs (-3, 1.4) without using regular expressions, s = ’(-3, 1.4 )’ re, im = s[1:-1].split(’,’) � www.simula.no/˜hpl � www.simula.no/˜hpl c c About this course – p. 9 About this course – p. 10 The same function in C++ The relation to OOP Templates can be used to mimic dynamically typed Object-oriented programming can also be used to languages parameterize types Introduce base class A and a range of subclasses, all Not as quick and convenient programming: with a (virtual) print function template <class T> void debug(std::ostream& o, Let debug work with var as an A reference const std::string& leading_text, const T& variable) Now debug works for all subclasses of A { char* c = getenv("MYDEBUG"); Advantage: complete control of the legal variable types bool defined = false; if (c != NULL) { // if MYDEBUG is defined ... that debug are allowed to print (may be important in if (std::string(c) == "1") { // if MYDEBUG is true ... big systems to ensure that a function can allow make defined = true; } transactions with certain objects) } if (defined) { Disadvantage: much more work, much more code, less o << leading_text << " " << variable << std::endl; reuse of debug in new occasions } } � www.simula.no/˜hpl c � www.simula.no/˜hpl c About this course – p. 11 About this course – p. 12 Keyword arguments Flexible function interfaces User-friendly environments (Matlab, Maple, Keyword arguments = function arguments with Mathematica, S-Plus, ...) allow flexible function keywords and default values, e.g., interfaces def plot(data, label=’’, xrange=None, title=’’, linetype=’solid’, linecolor=’black’, ...) Novice user: # f is some data The sequence and number of arguments in the call can plot(f) be chosen by the user More control of the plot: plot(f, label=’f’, xrange=[0,10]) More fine-tuning: plot(f, label=’f’, xrange=[0,10], title=’f demo’, linetype=’dashed’, linecolor=’red’) � www.simula.no/˜hpl � www.simula.no/˜hpl c c About this course – p. 13 About this course – p. 14 Testing a variable’s type Classification of languages (1) Inside the function one can test on the type of argument Many criteria can be used to classify computer provided by the user languages xrange can be left out (value None ), or given as a Dynamically vs statically typed languages 2-element list (xmin/xmax), or given as a string Python (dynamic): ’xmin:xmax’, or given as a single number (meaning c = 1 # c is an integer 0:number) etc. c = [1,2,3] # c is a list C (static): if xrange is not None: # i.e. xrange is specified by the user if isinstance(xrange, list): # list [xmin,xmax] ? double c; c = 5.2; # c can only hold doubles xmin = xrange[0]; xmax = xrange[1] c = "a string..." # compiler error elif isinstance(xrange, str): # string ’xmin:xmax’ ? xmin, xmax = re.search(r’(.*):(.*)’,xrange).groups() elif isinstance(xrange, float): # just a float? xmin = 0; xmax = xrange � www.simula.no/˜hpl c � www.simula.no/˜hpl c About this course – p. 15 About this course – p. 16
Recommend
More recommend