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/ : 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 () 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 ■ 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 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 ■ Iteration language concepts X J ■ Puzzles ■ XML ■ Data Structures ■ 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 programs. It is concerned with systems rather than and technological spaces software technologies languages as well as with other than programming languages.software 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 . 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 l = new LinkedList(); 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 { 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 well. More fun on “!”

How (not) to write Factorial in Java. http://chaosinmotion.com/blog/?p=622 The Shapes chrestomathy

With imports and inspiration from http://www.angelfire.com/tx4/cus/shapes/ The Shapes chrestomathy

There are different kinds of shapes: circles, rectangles, and possibly more (e.g., squares).

There is a polymorphic method: draw - for drawing a shape (e.g., on a canvas).

What different program designs are conceivable?

How to accomplish squares in the presence of shapes? Members of the chrestomathy

classy class Shape interfacy interface Shape enumy 1 class + 1 enum type classy.withSquares.sibling Square extends Shape classy.withSquares.sup Rectangle extends Square classy.withSquares.sub Square extends Rectangle Exercises

Try to explain the differences between classy, interface, enumy in more detail. Describe pros and cons of the approaches. Assess the different withSquares approaches. Describe pros and cons of the approaches. Would you eliminate any of them? Would you add another approach? Demo

All chrestomathies from the lecture are available online: https://github.com/rlaemmel/nopetal http://101companies.org/ The 101companies Software Chrestomathy http://101companies.org/

A community and research project with participation by the Software Languages Team in Koblenz. 101companies is concerned with programs. It is concerned with systems rather than and technological spaces software technologies languages as well as with other than programming languages.software Software technologies

GHCi Eclipse NUnit MySQL ANTLR LogicBlox make GHCEMF JAXB xjc JAXP Android Hibernate XMLHttpRequest XAMPP Pharo Saxon WCF JDBC HDBC Swing GWT HSQLDB Struts AntSilverlight ODBC HXT Hadoop QTCreator AWT SAX wxHaskell BaseX Heist MongoDB JUnit jQuery Maven ajc DBDirect GReTL OpenCOBOL Kiama Parsec DOM AJDT Happstack Pyjamas CGI JSF xsltproc Graphviz GlassFish Neo4jIndexedDB HaskellDB JDOM Xtext XMLStreamWriter Ecore DPH Seaside NetBeans XOM Rebar Seam megalib RMI-IIOP csc.exe Microsoft PowerPoint basename MediaWikiRefactorer LINQ Java Servlet API JNDI CSharpValidator WP7 SDK XmlReaderW3CValidator Dropsbox Ruby on Rails XSDValidator Document-oriented database ECS Haskell platform SVN GNU make 101worker Jetty JFactExtractor MSBuild JAF Java Print Service JGroups JGraph LINQ to XML jEdit HTTP JDK Rhino Zend framework Apache HTTP Server Internet Explorer JDT dirname Hamcrest Android Development Tool SQL Server TCP GeSHi JAMA Safari XmlFragmentLocator JMF OSCache JFragmentLocator Java misc Bouncy Castle DLL Lucene Glade Apache Tomcat JTA Javassist Java eventsMercurial MoDisco Entity Framework Java Image I/O iText Erlang/OTP Guava JBoss Application Server MOF HTML Parser javac Visual Studio Google Chrome JValidator wxWidgets Smack ArgoUML Apache Commons ASP .NET MVC JSP BSF HackageDB fcs.exeASM GeFLo JGoodies simplejson ASP .NET Opera XA Sqlite XStream Servlet API Java Media APIs Velocity CSharpFragmentLocator WPF CLR XMLValidator Apache XML-RPC HsImportMatcher Java EE .NET XML Serialization ORO 101explorer Jaxen Tidy .NETJavaMail JFreeChart OGNL Java Bean Jython Java SE dom4j Java Servlet NORMA CUP SLF4J Avalon Nix Web storage Xalan-Java CVS log4j Object Streams Microsoft Excel EJB Java collections XML pickler java.util.Scanner Java platform BCEL HPC POIMozilla Firefox Balsamiq Mockups HsFragmentLocator Cabal LINQ to SQL JPA Spring xsd.exe Facelets Android SDK gzip

© 2012, 101companies Software languages

Java XML Haskell JavaScript CSharp SQL CSS HTML XSD Ecore HTML5 DatalogLB JSON PHP ATL XMI XHTML Scala Groovy HQL Python Ruby Smalltalk XPath XSLTErlang AspectJ XQuery HSQLDialect EBNF GReTL CPlusPlus Prolog WSDL FSharp Cobol EXE Zip Java manifest file Rascal Launch file MegaL Haskell 98 OGNL UML Config JNLP Plain text SWF tar XLS Shell Script Java bytecode AWK SVG ODF xjc POJOs ICO Sass Settings Datalog BMML JPEG DLL GIF VB.NET 101meta PDF BSON CSV BNF Cobol 85 Markdown protobuf JAXB annotations RAR YAML PNG Unicode gzip JAR ASCII

© 2012, 101companies Contributions implement the 101companies system.

“101 ways of building a HRMS.”

Company X: Swing + JDBC

Company Y: SWT + Hibernate

Company Z: GWT + MongoDB

... • Total salaries • Increase salaries • Cut salaries • Edit employee data • ... © 2012, 101companies Contribution:javaInheritance Basic OO programming in Java

Languages ■ Java Technologies ■ Eclipse ■ JUnit Features ■ Tree structure ■ Type-driven query ■ Type-driven transformation Motivation Basic style of OO programming is applied. A simple object model for companies is provided with methods to implement a query for totaling salaries and a transformation for cutting salaries. In fact, class inheritance is leveraged, but see 101implementation:javaComposition for a variation that uses object composition. Because of the use of class inheritance, the aforementioned methods are actually virtual methods. Closed serialization in the sense of Object Streams is enabled by means of the marker interface Serializable, which is applied to the classes of the object model for companies. Wrap up Challenges

Contribution process (encouragement) Contribution quality (automation) Community involvement (contribution, validation) Co-evolutionary changes ... Join the Software Languages Team!