OCAML FROM THE VERY BEGINNING



Similar documents


Copyright 1980 by the Association for Supervision and Curriculum Development. All rights reserved.




Publishing Scholarly Papers. NURS Fall, 2015

The Disappearance of the Social in American Social Psychology

Symbolism and Regime Change in Russia

Primary Mathematics. Capitalising on ICT for today and tomorrow

Advanced Grammar in Use

!"#$%&##'()$*"&))& ''''+!,'-%)&./&0$1)&'+21.0


Week 3. COM1030. Requirements Elicitation techniques. 1. Researching the business background

Gendering the International Asylum and Refugee Debate

Cambridge IELTS 2. Examination papers from the University of Cambridge Local Examinations Syndicate

English for Business Communication

Cambridge IELTS 3. Examination papers from the University of Cambridge Local Examinations Syndicate

Approaches and Methods in Language Teaching

The Advantages and Disadvantages of an Independent Major

One Day. Helen Naylor. ... Level 2. Series editor: Philip Prowse. Cambridge University Press One Day.

Contents. Table of Statutes. Table of Secondary Legislation. Table of Cases. Pre-action Conduct of Litigation

Related guides: 'Planning and Conducting a Dissertation Research Project'.

How to Become a Clinical Psychologist

Switching and Finite Automata Theory

How do you use word processing software (MS Word)?

Disability and Carers Service. Customer Information

Equality in Education Law and Policy,

Human Rights and Social Work

Introductory Problem Solving in Computer Science

GOAL: Perform Current Job Tasks Better

Tomiko Hale School of Engineering, UC Merced

PROGRAM LOGICS FOR CERTIFIED COMPILERS

Presentation on the European Law School, Prof. Dr. Martin Heger, Humboldt Universität Berlin TDP Workshop, Berlin, April 18-20, 2008

HA 511: Leadership in Healthcare Administration Syllabus

Getting your news out: Preparing your. Press Release. Using a press release. Other publications options. How to deal with queries.

Social Media Intelligence

Psychic Tarot Reading

CRUSH WHITE PAPER HOW TO BUILD A KILLER STRATEGIC ACCOUNT PLAN. The guide every salesperson needs to read before creating a strategic account plan.

PROGRAMME SPECIFICATION

How to Sell Yourself in a Job Interview

Review Your Thesis or Dissertation

debt Managing debt Easy to get into, harder to get out Inside... Think before you borrow Know your options Make a debt repayment plan

Consult Yourself. The NLP Guide to Being a Management Consultant. Carol Harris

Town Of Concord. APP #45 Telephone Procedures, Policies & Guidelines. The Caller's Bill of Rights

Outline. Written Communication Conveying Scientific Information Effectively. Objective of (Scientific) Writing

Professor Marilyn Fleer

What happens to my application form? How do I apply? Completing the form

Managing debt. It s easy to get into, harder to get out. Inside... debt. Think before you borrow. Know your options. Make a debt repayment plan

Create a Basic Skype* Account. Intel Easy Steps Intel Corporation All rights reserved.

Starting In Business. Are you sure?

How to write a good (maths) Ph.D. thesis

Exercise: Effective Customer Care and Communication for Call Center Agents

Writing a Good College Application Essay. Most Important

Msc Thesis Project Civil Engineering and Management

How to Write a Compelling Personal Statement. Be True to Your Voice. What Format Should You Use? What Story Should You Tell?

Preface to the Second Edition

Cyber Security and the Politics of Time

GRADUATE SCHOOL INFORMATION

superseries FIFTH EDITION

S u m m a ry Judgment and S u m m a ry Trials in Supreme Court

SECURITY AND QUALITY OF SERVICE IN AD HOC WIRELESS NETWORKS

MATHEMATICAL LOGIC FOR COMPUTER SCIENCE

MORTALITY AMONGST ILLICIT DRUG USERS

Determining Students Language Needs in a Tertiary Setting

Teacher s Book Gareth Knight Mark O Neil

NANOCOMPUTING. Computational Physics for Nanoscience and Nanotechnology

GRADE 5 SUPPLEMENT. Set A2 Number & Operations: Primes, Composites & Common Factors. Includes. Skills & Concepts

MODULE CO-ORDINATOR HANDBOOK. Collaborative Partners

Building Your Brand with LinkedIn

A Review of Ratings Analysis: Theory and Practice

ACCESSING WEB ARCHIVES

Citizen Leadership happens when citizens have power, influence and responsibility to make decisions

Strong Answers to Top 10 Interview Questions

Business Management. Business Information and ICT. Student Notes [INTERMEDIATE 1] NATIONAL QUALIFICATIONS CURRICULUM SUPPORT

THE MOORE METHOD: ITS IMPACT ON FOUR FEMALE PhD STUDENTS

Contents. Table of Statutes. Table of Secondary Legislation. Table of Cases. Understanding Undefended Debt Claims. Enforcement of Money Judgments

Digital Handbook: About the Master of Arts in History Contact: Paul Christopher Anderson, Graduate Coordinator

UCC Writing Survey of Students

Model Assignment Issued September 2009

!"#$%&'()"*"++%(*,%-")+.*(#%/"0"#.12"*3

Camferfoge plain Cext*

Transcription:

OCAML FROM THE VERY BEGINNING In OCaml from the Very Beginning John Whitington takes a no-prerequisites approach to teaching a modern general-purpose programming language. Each small, selfcontained chapter introduces a new topic, building until the reader can write quite substantial programs. There are plenty of questions and, crucially, worked answers and hints. OCaml from the Very Beginning will appeal both to new programmers, and experienced programmers eager to explore functional languages such as OCaml. It is suitable both for formal use within an undergraduate or graduate curriculum, and for the interested amateur. JOHN WHITINGTON founded a software company which uses OCaml extensively. He teaches functional programming to students of Computer Science at the University of Cambridge.

OCAML from the very beginning John Whitington C O H E R E N T P R E S S

C O H E R E N T Cambridge P R E S S Published in the United Kingdom by Coherent Press, Cambridge Coherent Press 2013 This publication is in copyright. Subject to statutory exception no reproduction of any part may take place without the written permission of Coherent Press. First published 2013 A catalogue record for this book is available from the British Library ISBN 978-0-9576711-0-2 Paperback

Contents Getting Ready ix 1 Starting Off 1 2 Names and Functions 9 Note on Notation 17 3 Case by Case 19 4 Making Lists 25 Two Different Ways of Thinking 35 5 Sorting Things 37 Loading a Program from a File 45 6 Functions upon Functions upon Functions 47 7 When Things Go Wrong 55 8 Looking Things Up 61 9 More with Functions 67 10 New Kinds of Data 73 11 Growing Trees 81 12 In and Out 89 13 Putting Things in Boxes 99 14 The Other Numbers 111 15 The OCaml Standard Library 117 16 Building Bigger Programs 123 Answers to Questions 133 Hints for Questions 179 Coping with Errors 187 Index 191 v

Preface This book is based on the Author s experience of teaching programming to students in the University of Cambridge supervisions system. In particular, working with students for the first-year undergraduate course Foundations of Computer Science, based on Standard ML and lectured for many years by Lawrence C. Paulson. An interesting aspect of supervising students from a wide range of backgrounds (some with no previous experience at all taking Computer Science as an additional subject within the Cambridge Natural Sciences curriculum, and some with a great deal of programming experience already) is the level playing field which the ML family of languages (like OCaml) provide. Sometimes, those students with least prior programming experience perform the best. I have tried to write a book which has no prerequisites and with which any intelligent undergraduate ought to be able to cope, whilst trying to be concise enough that someone coming from another language might not be too annoyed by the tone. Special note to those who have already written programs When I was a boy, our class was using a word processor for the first time. I wanted a title for my story, so I typed it on the first line and then, placing the cursor at the beginning, held down the space bar until the title was roughly in the middle. My friend taught me how to use the centring function, but it seemed more complicated to me, and I stuck with the familiar way after all, it worked. Later on, of course, when I had more confidence and experience, I realized he had been right. When starting a language which is fundamentally different from those you have seen before, it can be difficult to see the advantages, and to try to think of every concept in terms of the old language. I would urge you to consider the possibility that, at the moment, you might be the boy holding down the space bar. Acknowledgments Inevitably, the approach here owes a debt to that taken by Lawrence C. Paulson, both in his lecture notes and in his book ML for the Working Programmer (Cambridge University Press, 1996). Question 3 in Chapter 11 is inspired by an examination question of his. I was taught Standard ML by Professor Paulson and Andrei Serjantov in Autumn 2000. Mark Shinwell has been a constant source of helpful discussion. Robin Walker and latterly Andrew Rice have arranged the supervisions system at Queens College within which I have taught since 2004. I am grateful to the developers of OCaml who have provided such a pleasant environment in which to write programs. Helpful comments on an earlier draft were provided by Martin DeMello, Damien Doligez, Arthur Guillon, Zhi Han, Robert Jakob, Xavier Leroy, Florent Monnier, and Benjamin Pierce. And, of course, I thank all my students, some of whom are now working with OCaml for a living. vii

Getting Ready This book is about teaching the computer to do new things by writing computer programs. Just as there are different languages for humans to speak to one another, there are different programming languages for humans to speak to computers. We are going to be using a programming language called OCaml. It might already be on your computer, or you may have to find it on the internet and install it yourself. You will know that you have OCaml working when you see something like this: # OCaml OCaml is waiting for us to type something. Try typing 1 space + space 2 ; ; followed by the Enter key. You should see this: OCaml # 1 + 2;; - : int = 3 OCaml is telling us the result of the calculation. To leave OCaml, give the exit 0 command, again ending with ;; to tell OCaml we have finished typing: # exit 0;; OCaml You should find yourself back where you were before. If you make a mistake when typing, you can press Ctrl-C (hold down the Ctrl key and tap the c key). This will allow you to start again: OCaml # 1 + 3^CInterrupted # 1 + 2;; - : int = 3 We are ready to begin. ix