Java Version
Total Page:16
File Type:pdf, Size:1020Kb
http://blogs.guardian.co.uk/digitalcontent/wham20dec2007.jpg M Xmess lecture 2012/13 Professor Fish University of Koblenz-Landau Program Chrestomathies All chrestomathies from the lecture are available online: https://github.com/rlaemmel/nopetal http://101companies.org/ [http://en.wikipedia.org/wiki/Chrestomathy, 16 December 2012] Program Chrestomathies Hello World: http://www.roesler-ac.de/wolfram/hello.htm 99 bottles of beer: http://99-bottles-of-beer.net/ Factorial: http://www.willamette.edu/~fruehr/haskell/evolution.html Fibonacci sequence: http://cubbi.com/fibonacci.html OO shapes: http://www.angelfire.com/tx4/cus/shapes/ Literate programs: http://en.literateprograms.org/ Rosetta Code: http://rosettacode.org/ 101companies: http://101companies.org/ See also http://rosettacode.org/wiki/Help:Similar_Sites for more chrestomathies! Hello World http://www.roesler-ac.de/wolfram/hello.htm 99 bottles of beer 99 bottles of beer Some Java version http://www.99-bottles-of-beer.net/language-java-4.html?PHPSESSID=32269dee0fedac31dc90739c31ab45f9 class bottles { public static void main(String args[]) { String s = "s"; for (int beers=99; beers>-1;) { System.out.print(beers + " bottle" + s + " of beer on the wall, "); System.out.println(beers + " bottle" + s + " of beer, "); if (beers==0) { System.out.print("Go to the store, buy some more, "); System.out.println("99 bottles of beer on the wall.\n"); System.exit(0); } else System.out.print("Take one down, pass it around, "); s = (--beers == 1) ? "" : "s"; System.out.println(beers + " bottle" + s + " of beer on the wall.\n"); } } } The evolution of a Haskell programmer http://www.willamette.edu/~fruehr/haskell/evolution.html Many implementations of the “!” function Freshman Haskell programmer Accumulating Haskell programmer Sophomore Haskell programmer, at MIT Continuation-passing Haskell programmer Junior Haskell programmer Boy Scout Haskell programmer Senior Haskell programmer Combinatory Haskell programmer Memoizing Haskell programmer List-encoding Haskell programmer Pointless Haskell programmer Interpretive Haskell programmer Iterative Haskell programmer ... Freshman Haskell programmer http://www.willamette.edu/~fruehr/haskell/evolution.html fac n = if n == 0 then 1 else n * fac (n-1) Fibonacci sequence http://cubbi.com/fibonacci.html Consider different complexities and approaches Exponential complexity Linear complexity Cached binary recursion / memoization Cached linear recursion / lazy evaluated list Linear recursion with accumulator Imperative loop with mutable variables Logarithmic complexity Matrix multiplication Fast recursion Binet’s formula with rounding Examine languages for different approaches Linear recursion with accumulator (x: argument; y:time in seconds) OO shapes http://www.angelfire.com/tx4/cus/shapes/ Use an OO-centric programming problem. Rectangles and circles as shapes. Subtype-specific behavior for drawing. Polymorphic processing of shape containers. Show how to address the problem in non-OO languages. Enjoy “Haskell's overlooked object system”: http://homepages.cwi.nl/~ralf/OOHaskell/ Literate programs http://en.literateprograms.org/ LiteratePrograms:Welcome Welcome to LiteratePrograms! LiteratePrograms is a unique wiki where every article is simultaneously a document and a piece of code that you can view, download, compile, and run by simply using the "download code" tab at the top of every article. See Insertion sort (C) for a simple example. To date we have 182 articles. Based on Donald Knuth's concept of literate programming, LiteratePrograms is a collection of code samples displayed in an easy-to-read way, collaboratively edited and debugged, and all released under the liberal MIT/X11 License (see Copyrights) so that anyone can use our code and text for any purpose. Code on LiteratePrograms is organized in a variety of ways using categories: by subject area, by language, by environment, and so on. Following are some of the top- level category lists to get you started. If you're interested in contributing your own programs, you can read about how to write an article. You don't need to know literate programming to contribute! Part of insertion sort for C Rosetta Code http://rosettacode.org Many programming tasks (617) Many languages (483) Wiki-based Community-driven Rosetta Code: Top-level categories of tasks 3 ■ Environment variables ■ Logic ■ 3D F M A ■ File handling ■ Mathematical S operations ■ Flow control ■ Sciences ■ Animation ■ Mathematics ■ Arithmetic ■ Functions and ■ Scope subroutines ■ Memory management B ■ Screen capture G N ■ Signal handling ■ Basic language ■ Networking and Web ■ Software Engineering learning ■ Game engine Interaction ■ Sorting C ■ Games ■ Geometric Primitives O ■ Speech Recognition ■ Checksums ■ Geometric Subtraction ■ Object oriented ■ Speech synthesis ■ Classic CS problems ■ Graphics algorithms P ■ Streams and programs ■ GUI ■ String manipulation ■ Pointing devices ■ Compression I T ■ Concurrency ■ Programming ■ Temporal media ■ Conditional loops ■ Image processing environment ■ Terminal control ■ Constructive Solid ■ Initialization operations ■ Text processing Geometry ■ Internet Protocol ■ Programming D ■ Iteration language concepts X J ■ Puzzles ■ XML ■ Data Structures R ■ Database operations ■ Joystick ■ Date and time K ■ Randomness ■ Recursion E ■ Keyboard Input ■ Regular expressions ■ Encryption L ■ Rosetta Code related 101companies/ http://101companies.org A community and research project with participation by the Software Languages Team in Koblenz. 101companies is concerned with systems rather than programs. It is concerned with software technologies and technological spaces as well as with software languages other than programming languages. Why are people doing this? I am making this all up! Chrestomathies don’t exist!? People have too much time on their hands!? This is fun for programming nerds! This actually helps understanding programming & languages! This is the art of programming!? The NOP chrestomathy Made up for this lecture ! [http://en.wikipedia.org/wiki/NOP, 16 December 2012] Arguably, we may also want to see the “complete” program that effectively does nothing at al.. NOP in Java $ more Program.java class Program { public static void main(String[] args) { } } $ javac Program.java $ java Program $ NOP in C (with GCC) $ more Program.c main() { For what matters, this program may } return a non-zero $ gcc Program.c return code. $ ./a.out $ NOP in C (with GCC) $ more Program.c main() { return 0; Variation with } return code $ gcc Program.c “0”. $ ./a.out $ NOP in Haskell (with GHC) $ more Program.hs main = do return () $ ghc -v0 Program.hs $ ./Program $ NOP in Python (interpreted) $ more Program.py $ python Program.py $ NOP in Python (scripted) $ more Program.py #! /usr/bin/env python $ ./Program.py $ What does this teach us? Java is a class-oriented programming language. C is a procedural programming language. Haskell is a functional programming language. Python is a scripting language. What does this teach us? Java is a compiled language. C is a compiled language. Haskell is a compiled language. Python is an interpreted language. The Factorial chrestomathy Haskell snippets and general idea inspired by F. Ruehr’s “Evolution of a Haskell programmer”. Freshman Haskell programmer http://www.willamette.edu/~fruehr/haskell/evolution.html fac n = if n == 0 then 1 else n * fac (n-1) Java counterpart Never trust Never trust type the filenames! inference, rather over-specify! public class HaskellFreshman { public static long fac(int n) { Use many if (n == 0) keywords to return 1; Parentheses compensate impress grandma! else for language’s lack of return n * fac(n-1); confidence! } } Where is “then”? Te n u r e d p ro f e s s o r http://www.willamette.edu/~fruehr/haskell/evolution.html fac n = product [1..n] Wow, one can Wow, one can multiply all numbers enumerate in a in a list! range! Java counterpart; 1st attempt public class HaskellProfessor { public static long fac(int n) { List<Integer> l = new LinkedList<Integer>(); for (int i=1; i<=n; i++) l.add(i); long result = 1; for (int x : l) result *= x; return result; We lack abstractions: } [1..n] } product Java counterpart; 2nd attempt public class HaskellProfessor { public static long fac(int n) { return new IntList(1,n).product(); } } We dream up a We place an instance constructor that method for “product” serves an int range. in the IntList class. import java.util.LinkedList; public class IntList extends LinkedList<Integer> { public IntList() { super(); } Perhaps, we public IntList(int from, int to) { super(); wanted this for all for (int i=from; i<=to; i++) int-like or, in fact, add(i); all enum types? } public long product() { long result = 1; for (int x : this) Well, this method result *= x; only works for return result; number-like types. } } Factorial in Java: idiomatically, iteratively, imperatively public class JavaStyle { public static long fac(int n) { long result = 1; for (int i=1; i<=n; i++) result *= i; return result; } } Haskell counterpart -- WTF! import Data.IORef fac n = do resultRef <- newIORef 1 iRef <- newIORef 1 for iRef (<=n) (+1) (do i <- readIORef iRef modifyIORef resultRef (*i)) result <- readIORef resultRef return result where for ref cond adjust body = do val <- readIORef ref if cond val then do body modifyIORef ref adjust for ref cond adjust body else return () What does this teach us? Haskell has some simple abstractions Java hasn’t. Encoding Haskell’s abstractions in Java isn’t easy. Mimicking a language’s idioms may not work too