Lecture Notes in Computer Science 6299 CommencedPublicationin1973 FoundingandFormerSeriesEditors: GerhardGoos,JurisHartmanis,andJanvanLeeuwen EditorialBoard DavidHutchison LancasterUniversity,UK TakeoKanade CarnegieMellonUniversity,Pittsburgh,PA,USA JosefKittler UniversityofSurrey,Guildford,UK JonM.Kleinberg CornellUniversity,Ithaca,NY,USA AlfredKobsa UniversityofCalifornia,Irvine,CA,USA FriedemannMattern ETHZurich,Switzerland JohnC.Mitchell StanfordUniversity,CA,USA MoniNaor WeizmannInstituteofScience,Rehovot,Israel OscarNierstrasz UniversityofBern,Switzerland C.PanduRangan IndianInstituteofTechnology,Madras,India BernhardSteffen TUDortmundUniversity,Germany MadhuSudan MicrosoftResearch,Cambridge,MA,USA DemetriTerzopoulos UniversityofCalifornia,LosAngeles,CA,USA DougTygar UniversityofCalifornia,Berkeley,CA,USA GerhardWeikum MaxPlanckInstituteforInformatics,Saarbruecken,Germany Zoltán Horváth Rinus Plasmeijer Viktória Zsók (Eds.) Central European Functional Programming School Third Summer School, CEFP 2009 Budapest, Hungary, May 21-23, 2009 and Komárno, Slovakia, May 25-30, 2009 Revised Selected Lectures 1 3 VolumeEditors ZoltánHorváth EötvösLorándUniversity,FacultyofInformatics DepartmentofProgrammingLanguagesandCompilers PázmányPéterSétány1/C,1117Budapest,Hungary E-mail:[email protected] RinusPlasmeijer RadboudUniversity,ComputerandInformationSciencesInstitute Heyendaalseweg135,6525AJNijmegen,TheNetherlands E-mail:[email protected] ViktóriaZsók EötvösLorándUniversity,FacultyofInformatics DepartmentofProgrammingLanguagesandCompilers PázmányPéterSétány1/C,1117Budapest,Hungary E-mail:[email protected] LibraryofCongressControlNumber:2010940290 CRSubjectClassification(1998):D.1.1,D.3.2,F.3.3,D.1-2,D.1.5,C.2,F.4 LNCSSublibrary:SL1–TheoreticalComputerScienceandGeneralIssues ISSN 0302-9743 ISBN-10 3-642-17684-4SpringerBerlinHeidelbergNewYork ISBN-13 978-3-642-17684-5SpringerBerlinHeidelbergNewYork Thisworkissubjecttocopyright.Allrightsarereserved,whetherthewholeorpartofthematerialis concerned,specificallytherightsoftranslation,reprinting,re-useofillustrations,recitation,broadcasting, reproductiononmicrofilmsorinanyotherway,andstorageindatabanks.Duplicationofthispublication orpartsthereofispermittedonlyundertheprovisionsoftheGermanCopyrightLawofSeptember9,1965, initscurrentversion,andpermissionforusemustalwaysbeobtainedfromSpringer.Violationsareliable toprosecutionundertheGermanCopyrightLaw. springer.com ©Springer-VerlagBerlinHeidelberg2010 PrintedinGermany Typesetting:Camera-readybyauthor,dataconversionbyScientificPublishingServices,Chennai,India Printedonacid-freepaper 06/3180 Preface Thisvolumepresentstherevisedlecturenotesofselectedtalksgivenatthethird CentralEuropeanFunctionalProgrammingSchool,CEFP2009,heldduring25– 30 May in Koma´rno (Slovakia) at Selye Ja´nos University. It was co-organized with the TFP 2009 conference. The summer school included a three-day warm- up session organized at Eo¨tvo¨s Lora´nd University, Budapest, Hungary during 21–23 May, 2009. The summer school was organized in the spirit of the advanced program- ming schools. CEFP focuses on involving an ever-growing number of students, researchers, and teachers from Central- and Eastern-European countries. The intensive program offered a creative and inspiring environment and a great opportunity to present and exchange ideas on new topics of functional programming. Thelecturescoveredawiderangeofsubjectslikedesignpatterns,semantics, types,andadvancedprogramminginvariousfunctionalprogramminglanguages. We are very grateful to the lecturers and researchers for the time and the effort they devoted to the talks and the revised lecture notes. The lecture notes were each carefully checked by reviewers selected from experts on functional programming. Afterwards the papers were revised once more by the lecturers. This revision process guaranteed that only high-quality papers were accepted for the volume. ThelasttwopapersofthevolumeareselectedpapersfromthePhDworkshop of the summer school. Wewouldliketoexpressourgratitudefortheworkofallthemembersofthe ProgramCommittee and the Organizing Committee. The web-page for the summer school can be found at http://www.inf.elte.hu/english/conf/tfp cefp 2009/ August 2010 Zolta´n Horva´th Rinus Plasmeijer Vikto´ria Zso´k Organization CEFP2010wasco-organizedbytheSelyeJ´anosUniversity,Koma´rno(Slovakia) and Eo¨tvo¨s Lora´nd University, Budapest, Hungary. Sponsoring Institutions The summer school was supported by the CEEPUS program(via the CEEPUS CII-HU-19 Network) and by the two organizing universities. Table of Contents Rapid Prototyping of DSLs with F# ............................... 1 Adam Granicz Erlang Behaviours:Programming with Process Design Patterns........ 19 Francesco Cesarini and Simon Thompson Reasoning about Codata.......................................... 42 Ralf Hinze Programming in Manticore, a Heterogenous Parallel Functional Language ....................................................... 94 Matthew Fluet, Lars Bergstrom, Nic Ford, Mike Rainey, John Reppy, Adam Shaw, and Yingqi Xiao Non-monadic Models of Mutable References ......................... 146 P´eter Divia´nszky Software Testing with QuickCheck ................................. 183 John Hughes An Effective Methodology for Defining Consistent Semantics of Complex Systems ................................................ 224 Pieter Koopman, Rinus Plasmeijer, and Peter Achten Types for Units-of-Measure: Theory and Practice .................... 268 Andrew Kennedy Functional Programmingwith C++ Template Metaprograms.......... 306 Zolt´an Porkol´ab Embedding a Proof System in Haskell .............................. 354 Gergely D´evai Impact Analysis of Erlang Programs Using Behaviour Dependency Graphs ......................................................... 372 Melinda To´th, Istva´n Boz´o, Zolt´an Horv´ath, L´aszlo´ L¨ovei, Ma´t´e Tejfel, and Tama´s Kozsik Author Index.................................................. 391 Rapid Prototyping of DSLs with F# Adam Granicz IntelliFactory, Budapest, Hungary [email protected] http://www.intellifactory.com Abstract. In theselecture notes wepresent theF# implementation of a small programming language we call Simply. We give the parser im- plementation using active patterns, F#’s unique feature for extensible patternmatching,whichaswedemonstrateprovideanelegantandtype- safe mechanism to embed parsers as an alternative approach to parser generators. Wealso build anevaluator, and extendthecoreSimply lan- guage with Logo-like primitives andbuild agraphical shellenvironment around it. As a warm-up, we give a rudimentary survey of some notable F# features,includingsequenceexpressionsandactivepatterns.Foratreat- ment of units of measure, used briefly in the Simply shell environment, thereader is encouraged to study[AK-09] and [AK-CEFP-09]. 1 F# F#isastaticallytype-checked,type-inferred,script-likefunctionalprogramming language for the .NET framework. It supports object-oriented and imperative programming, and comes with built-in language features for asynchronous and metaprogramming [DS-06]. For more information about F# refer to [DS-09]. 1.1 Getting Started with F# Most of the examples in this warm-up section and the later sections on DSL developmentcanbetypedindirectlyintoF#Interactive,andinfact,thisisthe easiestwaytogetacquaintedwithF#.F#Interactivecanberunintwomodes: directly asa command-line toolbyinvokingfsi.exe,or inside VisualStudio as a plug-in - which is installed by default with the F# Visual Studio extensions (partofthe mainF#installer).As thelecturegoeson,itissuggestedto trythe exampleswithVisualStudio,byopeninganF#sandboxprojectandaddingF# source files to this project. Therefore, it is easy to interact with F# Interactive eitherbytypingcodeintotheF#Interactivewindow,orhighlightingsomecode in the editor window and pressing Alt+Enter. This Visual Studio command sends the highlighted text into F# Interactive, adding any new definitions into the currently running session. An F# Interactive session can be exited and restarted any time by typing ”exit 1;;” into the F# Interactive window. Z.Horv´ath,R.Plasmeijer,andV.Zs´ok(Eds.):CEFP2009,LNCS6299,pp.1–18,2010. (cid:2)c Springer-VerlagBerlinHeidelberg2010 2 A. Granicz 1.2 Sequences and Sequence Expressions Sequences are data that can be enumerated on demand - they are a lazy data structure. The F# data type seq<’T> is an alias for the .NET interface type IEnumerable<’T>, and effectively all of the .NET and F# collections are sequences. Sequences are a powerful abstraction in F# programming, and in fact they areusedtowrapallkindsofdatasourcesbesidesordinarycollections,including databases, LINQ queries for XML and relational data, and so on. F# provides rich support for sequences. Ordinary sequences of integers and real numbers can easily be constructed using the sequence notation: { 1 .. 100 } // All integers between 1 and 100. { 1.0 .. 100.0 } // All integers between 1 and 100 as doubles. { 1 .. 2 .. 100 } // All odd numbers between 1 and 100. Sequence comprehensions are a formalism to construct a sequence of values using a generator function: seq { for i in 1 .. 100 -> i*i } // The first 100 squares. This code is equivalent to seq { 1 .. 100 } |> Seq.map (fun i -> i*i) Sequenceexpressionsareaformofcomputationexpressionsorworkflows,F#’s unique feature that adds monadic syntax over F# code. Consider the example in Figure 1 that yields all the files in a given folder including those in all the subfolders. Note that subfolders are not searched until the sequence is enumerated, e.g. until the file names are actually consumed. In this expression, yield is used to return a single new element in the sequence, and yield! to return a sequence of elements. open System.IO let rec AllFiles dir = seq { for file in dir |> Directory.GetFiles do yield file for subdir in dir |> Directory.GetDirectories do yield! subdir |> AllFiles } Fig.1. Returningall files in a given folder as a sequence Rapid Prototyping of DSLswith F# 3 1.3 Pattern Matching and Active Patterns Pattern matching is a fundamental concept in functional programming. Take a look at the following code snippet: type Expr = | Integer of int | Binop of (int -> int -> int) * Expr * Expr let rec Eval = function | Integer i -> i | Binop (f, e1, e2) -> f (Eval e1) (Eval e2) Here, the type Expr is defined to be an algebraic data type (a variant or discriminateduniontype)withtwoshapes,eachcarryingdifferentvalues.These values can be extracted using pattern matching, and an example is given in the Eval function above. Active patterns [DS-07] are special functions that are applied on the value being matched before pattern matching actually takes place. As with ordinary patternmatching,activepatternsarestaticallycheckedforexhaustiveness.Their main advantage is that different conceptual views can be erected on any value, at any time, preserving encapsulation. Activepatternsaredefinedinsidepipes(andasurroundingsetofparentheses). Pattern cases can be closed or open (partial). Closed active patterns are made upofoneormorepatterncasesthatcollectivelycompletelydescribetheirinput, whereaspartialactivepatternsonlyattempttodescribepartsoftheinputvalue space. Converting Values. Single-caseactivepatternscanbe usedtoconvertvalues. Consider the following: open System let (|NiceString|) s = if s |> String.IsNullOrEmpty then NiceString "" else NiceString (s.Trim()) Here, NiceString is the only pattern case and thus it always matches in a pattern match: let _ = let (NiceString str) = " with whitespace " str |> printf "Result = [%s]\n"