Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

Programming Languages, Compilers and Interpreters - Lecture Slides | CMSC 330, Study Guides, Projects, Research of Programming Languages

Material Type: Project; Class: ORGNZTN PROGM LANG; Subject: Computer Science; University: University of Maryland; Term: Summer I 2008;

Typology: Study Guides, Projects, Research

Pre 2010

Uploaded on 07/30/2009

koofers-user-xqt
koofers-user-xqt 🇺🇸

10 documents

1 / 46

Toggle sidebar

Related documents


Partial preview of the text

Download Programming Languages, Compilers and Interpreters - Lecture Slides | CMSC 330 and more Study Guides, Projects, Research Programming Languages in PDF only on Docsity! 1 CMSC 330: Organization of Programming Languages Ruby 2 Reminders and Announcements • If you’re not on the list, you’re not in the class (I have the list) • Project 1 was posted on June 2 – It is due on June 11 – Start immediately • Check submit server access • Use the class forum • Read complete syllabus online • Leave 24 hours for email responses 5 Applications of Scripting Languages • Scripting languages have many uses – Automating system administration – Automating user tasks – Quick-and-dirty development • Major application: Text processing 6 Output from Command-Line Tool % wc * 271 674 5323 AST.c 100 392 3219 AST.h 117 1459 238788 AST.o 1874 5428 47461 AST_defs.c 1375 6307 53667 AST_defs.h 371 884 9483 AST_parent.c 810 2328 24589 AST_print.c 640 3070 33530 AST_types.h 285 846 7081 AST_utils.c 59 274 2154 AST_utils.h 50 400 28756 AST_utils.o 866 2757 25873 Makefile 270 725 5578 Makefile.am 866 2743 27320 Makefile.in 38 175 1154 alloca.c 2035 4516 47721 aloctypes.c 86 350 3286 aloctypes.h 104 1051 66848 aloctypes.o ... 7 Climate Data for IAD in August, 2005 ================================================================================ 1 2 3 4 5 6A 6B 7 8 9 10 11 12 13 14 15 16 17 18 AVG MX 2MIN DY MAX MIN AVG DEP HDD CDD WTR SNW DPTH SPD SPD DIR MIN PSBL S-S WX SPD DR ================================================================================ 1 87 66 77 1 0 12 0.00 0.0 0 2.5 9 200 M M 7 18 12 210 2 92 67 80 4 0 15 0.00 0.0 0 3.5 10 10 M M 3 18 17 320 3 93 69 81 5 0 16 0.00 0.0 0 4.1 13 360 M M 2 18 17 360 4 95 69 82 6 0 17 0.00 0.0 0 3.6 9 310 M M 3 18 12 290 5 94 73 84 8 0 19 0.00 0.0 0 5.9 18 10 M M 3 18 25 360 6 89 70 80 4 0 15 0.02 0.0 0 5.3 20 200 M M 6 138 23 210 7 89 69 79 3 0 14 0.00 0.0 0 3.6 14 200 M M 7 1 16 210 8 86 70 78 3 0 13 0.74 0.0 0 4.4 17 150 M M 10 18 23 150 9 76 70 73 -2 0 8 0.19 0.0 0 4.1 9 90 M M 9 18 13 90 10 87 71 79 4 0 14 0.00 0.0 0 2.3 8 260 M M 8 1 10 210 ... 10 Language Basics # This is a ruby program x = 37 y = x + 5 print(y) print("\n") comments begin with #, go to end of line variables need not be declared line break separates expressions (can also use “;” to be safe) no special main() function or method 11 Run Ruby, Run • There are three ways to run a Ruby program – ruby -w filename – execute script in filename • tip: the -w will cause Ruby to print a bit more if something bad happens – irb – launch interactive Ruby shell • can type in Ruby programs one line at a time, and watch as each line is executed irb(main):001:0> 3+4 => 7 irb(main):002:0> print("hello\n") hello => nil 12 Run Ruby, Run (cont’d) • Suppose you want to run a Ruby script as if it were an executable • ./filename # run program – The first line tells the system where to find the program to interpret this text file – Must chmod u+x filename first • Or chmod a+x filename so everyone has exec permission – Warning: Not very portable • Depends on location /usr/local/bin/ruby #!/usr/local/bin/ruby -w print("Hello, world!\n") 15 Methods in Ruby def sayN(message, n) i = 0 while i < n puts message i = i + 1 end return i end x = sayN("hello", 3) puts(x) List parameters at definition Invoke method May omit parens on call Methods are declared with def...end (Methods must begin with lowercase letter and be defined before they are called) 16 Method (and Function) Terminology • Formal parameters – The parameters used in the body of the method – message, n in our example • Actual parameters – The arguments passed in to the method at a call – "hello", 3 in our example 17 More Control Statements in Ruby • A control statement is one that affects which instruction is executed next – We’ve seen two so far in Ruby • while and function call • Ruby also has conditionals if grade >= 90 then puts "You got an A" elsif grade >= 80 then puts "You got a B" elsif grade >= 70 then puts "You got a C" else puts "You’re not doing so well" end 20 Using If and Unless as Modifiers • Can write if and unless after an expression – puts "You got an A" if grade >= 90 – puts "You got an A" unless grade < 90 • Why so many control statements? – Is this a good idea? – Advantages? Disadvantages? “syntactic sugar” 21 Other useful control statements case x when 1, 3..5 when 2, 6..8 end while i>n break next puts message redo end for i in (1..3) puts i end for elt in [1, “math”, 3.4] puts elt.to_s end (1..3).each { |elt| puts elt } IO.foreach(filename) { |x| puts x } generates a string. Also see to_i Code block does not need 'break' 22 To try with a neighbor Write (on paper) a Ruby function to print all even numbers from 1 to some given value x. def even(x) for i in (1..x) if i % 2 == 0 puts i end end end def even(x) (1..x).each{ |i| if i % 2 == 0 puts i end } end 25 Objects and Classes • Objects are data • Classes are types (the kind of data which things are) • But in Ruby, classes themselves are objects! • Fixnum, Float, String, etc., (including Class), are objects of type Class ClassObject ClassString ClassFixnum StringString.new String"CMSC 330" Float-3.30 Fixnum10 26 Two Cool Things to Do with Classes • Since classes are objects, you can manipulate them however you like – if p then x = String else x = Time end # Time is … # another class y = x.new # creates a String or a Time, # depending upon p • You can get names of all the methods of a class – Object.methods • => ["send", "name", "class_eval", "object_id", "new", "autoload?", "singleton_methods", ... ] 27 The nil Object • Ruby uses a special object nil – All uninitialized fields set to nil (@ refers to a class field) irb(main):004:0> @x => nil – Like NULL or 0 in C/C++ and null in Java • nil is an object of class NilClass – It’s a singleton object – there is only one instance of it • NilClass does not have a new method – nil has methods like to_s, but not other methods that don’t make sense irb(main):006:0> @x + 2 NoMethodError: undefined method `+' for nil:NilClass 30 Ruby is Dynamically Typed • Recall we don’t declare types of variables – But Ruby does keep track of types at run time x = 3; x.foo NoMethodError: undefined method 'foo' for 3:Fixnum • We say that Ruby is dynamically typed – Types are determined and checked at run time • Compare to C, which is statically typed # Ruby x = 3 x = "foo" # gives x a # new type /* C */ int x; x = 3; x = "foo"; /* not allowed */ 31 Types in Java and C++ • Are Java and C++ statically or dynamically typed? – A little of both – Many things are checked statically Object x = new Object(); x.println(“hello”); // No such method error at compile time – But other things are checked dynamically Object o = new Object(); String s = (String) o; // No compiler warning, fails at run time // (Some Java compilers may be smart enough to warn about above cast) 32 Tradeoffs? More programs type check Fewer programs type check Can use objects incorrectly and not realize until execution Helps prevent some subtle errors Less work when writing code More work to do when writing code Dynamic typesStatic types 35 Classes and Objects in Ruby (cont’d) • Recall classes begin with an uppercase letter • inspect converts any instance to a string irb(main):033:0> p.inspect => "#<Point:0x54574 @y=4, @x=7>" • Instance variables are prefixed with @ – Compare to local variables with no prefix – Cannot be accessed outside of class • The to_s method can be invoked implicitly – Could have written puts(p) • Like Java’s toString() methods 36 Inheritance • Recall that every class inherits from Object class A def plusplus(x) return x + 1 end end class B < A def plusplus(y) return (super(y) + 1) end end b = B.new puts(b.plusplus(3)) extend superclass invoke plusplus method of parent What is the output? 37 super() in Ruby • Within the body of a method, a call to super acts just like a call to that original method, except that the search for a method body starts in the superclass. 40 Creating Strings in Ruby • Substitution in double-quoted strings with #{} – course = "330"; msg = "Welcome to #{course}" – "It is now #{Time.new}" – The contents of #{} may be an arbitrary expression – Can also use single-quote to create strings ‘hi’ • No expression substitution, fewer escaped characters • Here-documents s = <<END This is a long text message on multiple lines and typing \\n is annoying END Can be any text no space no space 41 Creating Strings in Ruby (cont’d) • Ruby also has printf and sprintf – printf("Hello, %s\n", name); – sprintf("%d: %s", count, Time.now) • Returns a string • The to_s method returns a String representation of a class object 42 Standard Library: String • The String class has many useful methods – s.length # length of string – s1 == s2 # “deep” equality (string contents) – s = "A line\n"; s.chomp # returns "A line" • Return new string with s's contents except newline at end of line removed – s = "A line\n"; s.chomp! • Destructively removes newline from s • Convention: methods ending in ! modify the object • Another convention: methods ending in ? observe the object – "r1\tr2\t\tr4".each("\t") { |rec| puts rec } • Apply code block to each tab-separated substring 45 x "groundhog" (reference) (object) y "groundhog" x (reference) "groundhog" (object) y Deep vs. Shallow Equality • Consider these cases again: • If we compare x and y, what is compared? – The references, or the contents of the objects they point to? • If references are compared the first would return false but the second true • If objects are compared both would return true 46 String Equality • In Java, x == y is shallow equality, always – Compares references, not string contents • In Ruby, x == y for strings uses deep equality – Compares contents, not references – == is a method that can be overridden in Ruby! – To check shallow equality, use the equal? method • Inherited from the Object class • It’s always important to know whether you’re doing a deep or shallow copy – And deep or shallow comparison
Docsity logo



Copyright © 2024 Ladybird Srl - Via Leonardo da Vinci 16, 10126, Torino, Italy - VAT 10816460017 - All rights reserved