[PDF Download] Haskell school of music hudak p. full chapter pdf

Page 1


Haskell school of music Hudak P.

Visit to download the full and correct content document: https://textbookfull.com/product/haskell-school-of-music-hudak-p/

More products digital (pdf, epub, mobi) instant download maybe you interests ...

Historical Dictionary of Sacred Music Joseph P. Swain

https://textbookfull.com/product/historical-dictionary-of-sacredmusic-joseph-p-swain/

Thinking Functionally With Haskell Richard Bird

https://textbookfull.com/product/thinking-functionally-withhaskell-richard-bird/

Haskell The Ultimate Beginner s Guide to Learn Haskell

Programming Step by Step 1st Edition Claudia Alves

https://textbookfull.com/product/haskell-the-ultimate-beginner-sguide-to-learn-haskell-programming-step-by-step-1st-editionclaudia-alves/

Growing musicians : teaching music in middle school and beyond 1st Edition Sweet

https://textbookfull.com/product/growing-musicians-teachingmusic-in-middle-school-and-beyond-1st-edition-sweet/

Programming in Haskell 2nd Edition Graham Hutton

https://textbookfull.com/product/programming-in-haskell-2ndedition-graham-hutton/

Algorithm Design with Haskell Richard S. Bird

https://textbookfull.com/product/algorithm-design-with-haskellrichard-s-bird/

Music Theory Analysis and Society Selected Essays 1st Edition Robert P. Morgan

https://textbookfull.com/product/music-theory-analysis-andsociety-selected-essays-1st-edition-robert-p-morgan/

Handbook for Dragon Slayers 1st Edition Haskell Merrie

https://textbookfull.com/product/handbook-for-dragon-slayers-1stedition-haskell-merrie/

Hope and Wish Image in

David P. Rando (Auth.)

Music Technology 1st Edition

https://textbookfull.com/product/hope-and-wish-image-in-musictechnology-1st-edition-david-p-rando-auth/

TheHaskellSchoolofMusic —FromSignalstoSymphonies—

YaleUniversity DepartmentofComputerScience

Version2.5(January2013)

TheHaskellSchoolofMusic —FromSignalstoSymphonies— PaulHudak

YaleUniversity DepartmentofComputerScience NewHaven,CT,USA Version2.5(January2013)

Copyright c PaulHudak January2011,2012,2013 Allrightsreserved.Nopartofthispublicationmaybereproducedor distributedinanyformorbyanymeans,orstoredinadatabaseor retrievalsystem,withoutthepriorwrittenpermissionoftheauthor.

Coverimage: Euterpe,theGreekMuseofMusic (attributionunknown)

Preface xv

1ComputerMusic,Euterpea,andHaskell 1

1.1TheNotevs.SignalDichotomy .................2

1.2BasicPrinciplesofProgramming ................3

1.3ComputationbyCalculation ...................4

1.4ExpressionsandValues .....................8

1.5Types ...............................10

1.6FunctionTypesandTypeSignatures ..............11

1.7Abstraction,Abstraction,Abstraction .............13

1.7.1Naming ..........................13

1.7.2FunctionalAbstraction ..................16

1.7.3DataAbstraction .....................19

1.8HaskellEqualityvs.EuterpeanEquality ............22

1.9CodeReuseandModularity ...................23

1.10[Advanced]ProgrammingwithNumbers ............24

2.1Preliminaries ...........................28

2.2Notes,Music,andPolymorphism ................30

2.3ConvenientAuxiliaryFunctions

2.3.1ASimpleExample

2.4AbsolutePitches

3Polymorphic&Higher-OrderFunctions

3.1PolymorphicTypes ........................45

3.2AbstractionOverRecursiveDefinitions .............46

3.2.1MapisPolymorphic ...................48

3.2.2Usingmap ........................49

3.3Append ..............................50

3.3.1[Advanced]TheEfficiencyandFixityofAppend ...51

3.4Fold ................................52

3.4.1Haskell’sFolds

3.4.2[Advanced]WhyTwoFolds?

3.4.3FoldforNon-emptyLists ................56

3.5[Advanced]AFinalExample:Reverse .............57

3.6Currying ..............................59

3.6.1CurryingSimplification

3.6.2[Advanced]Simplificationof reverse ..........61

3.7Errors

4AMusicalInterlude

4.1Modules

4.2TranscribinganExistingScore

4.2.1AuxiliaryFunctions

4.2.2BassLine .........................71

4.2.3MainVoice ........................71

4.2.4PuttingItAllTogether .................72

4.3SimpleAlgorithmicComposition ................73 5SyntacticMagic

5.2AnonymousFunctions ......................78

5.3ListComprehensions

5.3.1ArithmeticSequences

5.4FunctionComposition

5.5Higher-OrderThinking

5.6InfixFunctionApplication ....................84

6MoreMusic 86

6.1DelayandRepeat .........................86

6.2InversionandRetrograde ....................87

6.3Polyrhythms ...........................89

6.4SymbolicMeterChanges .....................90

6.5ComputingDuration .......................91

6.6Super-retrograde .........................91

6.7 takeM and dropM ........................92

6.8RemovingZeros ..........................93

6.9TruncatingParallelComposition

6.9.1LazyEvaluationtotheRescue

6.10Trills ................................97

6.11GraceNotes ............................99

6.12Percussion .............................100

6.13AMapforMusic .........................102

6.14AFoldforMusic .........................104

6.15CrazyRecursion

7QualifiedTypesandTypeClasses

7.1Motivation ............................108

7.2Equality ..............................110

7.3DefiningOurOwnTypeClasses ................112

7.3.1DervivedInstances ....................113

7.3.2DefaultMethods .....................115

7.3.3Inheritance ........................116

7.4Haskell’sStandardTypeClasses ................118

7.4.1The Num Class ......................119

7.4.2The Show Class .....................120

7.4.3TheFunctorClass ....................123

7.5OtherDerivedInstances

7.6Thetypeof

7.7ReasoningWithTypeClasses

8.1AbstractPerformance

8.1.1Context

8.1.2PlayerMap

8.1.3Interpretation

8.1.4EfficiencyConcerns

8.2Players

8.2.1ExampleofPlayerConstruction

8.2.2DerivingNewPlayersFromOldOnes

8.2.3AFancyPlayer

9.1Self-SimilarMelody

9.1.1SampleCompositions

9.2Self-SimilarHarmony

9.3OtherSelf-SimilarStructures

10ProofbyInduction

10.1InductionandRecursion

10.2ExamplesofListInduction

10.3ProvingFunctionEquivalences

10.3.1[Advanced]Reverse

10.4.1[Advanced]FunctionStrictness .............163

10.5InductionontheMusicDataType ...............167

10.5.1TheNeedforMusicalEquivalence ...........170

10.6[Advanced]InductiononOtherDataTypes

10.6.1AMoreEfficientExponentiationFunction

11AnAlgebraofMusic

11.1.1LiteralPlayer

11.2SomeSimpleAxioms .......................179

11.3TheFundamentalAxiomSet ..................182

11.4AnAlgebraicSemantics

11.5OtherMusicalProperties

12MusicalL-SystemsandGenerativeGrammars

12.1GenerativeGrammars

12.1.1ASimpleImplementation

12.1.2AMoreGeneralImplementation

12.2AnL-SystemGrammarforMusic ................192

12.2.1Examples .........................193

13RandomNumbers...andMarkovChains

13.1RandomNumbers ........................196

13.2ProbabilityDistributions

13.2.1RandomMelodiesandRandomWalks

13.3MarkovChains ..........................205

13.3.1TrainingData

14.1.1GeneralMidi

14.1.2ChannelsandPatchMaps

14.1.3StandardMidiFiles ...................213

14.2ConvertingaPerformanceintoMidi ..............215

14.3PuttingItAllTogether

15.1IOinHaskell

15.2 do Syntax .............................221

15.3ActionsareJustValues .....................222

15.4ReadingandWritingMIDIFiles ................224

16Higher-OrderTypesandMonads

16.1TheFunctorClass ........................225

16.2The Monad Class .........................228

16.2.1OtherInstancesofMonad

16.2.2OtherMonadicOperations

16.3TheMonadPlusClass

16.4StateMonads ...........................237

16.5TypeClassTypeErrors

17.1Introduction ............................242

17.2BasicConcepts ..........................243

17.2.1TheTypeofaSignalFunction .............244

17.2.2 proc Declarations .....................245

17.2.3FourUsefulFunctions ..................246

17.2.4[Advanced]WhyArrows? ................246

17.3TheUISFArrow .........................247

17.3.1GraphicalInputandOutputWidgets

17.3.2WidgetTransformers ...................250

17.4EventsandMediators ......................252

17.4.1Mediators .........................253

17.4.2MIDIInputandOutput .................254

17.4.3MIDIDeviceIDs .....................255

17.4.4TimersandDelays ....................257

17.5AGraphicalCanvas .......................258

17.6PuttingItAllTogether

17.7MusicalExamples ........................258

17.7.1ChordBuilder ......................259

17.7.2ChaoticComposition ...................261

17.7.3MIDIEchoEffect .....................262

17.8GeneralI/OFromWithinaMUI ................263

18SoundandSignals 266

18.1TheNatureofSound .......................266

18.1.1FrequencyandPeriod ..................269

18.1.2AmplitudeandLoudness ................270

18.1.3FrequencySpectrum ...................274

18.2DigitalAudio ...........................276

18.2.1FromContinuoustoDiscrete ..............278

18.2.2Fixed-WaveformTable-LookupSynthesis .......280

18.2.3Aliasing ..........................281

18.2.4QuantizationError ....................284

18.2.5DynamicRange ......................286

19Euterpea’sSignalFunctions 288

19.1SignalsandSignalFunctions ..................289

19.1.1TheTypeofaSignalFunction .............291

19.1.2FourUsefulFunctions ..................293

19.1.3SomeSimpleExamples .................294

19.2GeneratingSound ........................299

19.3Instruments ............................300

19.3.1TurningaSignalFunctionintoanInstruement ....301

19.3.2Envelopes .........................303

20SpectrumAnalysis 307

20.1Fourier’sTheorem ........................307

20.1.1TheFourierTransform ..................309

20.1.2Examples .........................310

20.2TheDiscreteFourierTransform .................311

CONTENTS

20.2.1InterpretingtheFrequencySpectrum ..........314

20.2.2AmplitudeandPowerofSpectrum ...........316

20.2.3AHaskellImplementationoftheDFT .........318

20.3TheFastFourierTransform ...................324

20.4FurtherPragmatics ........................325

20.5References .............................326

21AdditiveSynthesisandAmplitudeModulation

21.1Preliminaries ...........................327

21.2ABellSound ...........................328

21.3AmplitudeModulation ......................331

21.3.1AMSoundSynthesis ...................332

21.4WhatdoTremoloandAMRadioHaveinCommon? .....333

AThePreludeListModule

A.1ThePreludeListModule .....................336

A.2SimpleListSelectorFunctions

A.3Index-BasedSelectorFunctions

A.4Predicate-BasedSelectorFunctions

A.5Fold-likeFunctions ........................339

A.6ListGenerators ..........................341

A.7String-BasedFunctions ......................341

A.8BooleanListFunctions ......................342

A.9ListMembershipFunctions ...................343

A.10ArithmeticonLists ........................343

A.11ListCombiningFunctions ....................344

BHaskell’sStandardTypeClasses

B.1TheOrderedClass ........................346

B.2TheEnumerationClass

B.3TheBoundedClass ........................348

B.4TheShowClass ..........................349

ListofFigures

1.1Polyphonicvs.ContrapuntalInterpretation ..........23

2.1GeneralMIDIInstrumentNames ................35

2.2ConvenientNoteNames .....................37

2.3ConvenientDurationandRestNames .............38

2.4ConvertingPitchClassestoIntegers ..............42

4.1ExcerptfromChickCorea’s ChildSongNo.6 .........69

4.2Bars7-28 .............................72

5.1GluingTwoFunctionsTogether .................82

6.1ASimpleMelodyandFourTransformations ..........88

6.2NestedPolyrhythms(top: pr 1 ;bottom: pr 2 ) .........89

6.3Trillsin StarsandStripesForever ...............99

6.4GeneralMIDIPercussionNames ................100

7.1CommonTypeClassesandTheirInstances ..........118

7.2NumericClassHierarchy .....................121

7.3StandardNumericTypes ....................122

7.4Euterpea’sDataTypeswithDerivingClauses .........125

8.1Anabstract perform function ..................134

8.2BlockDiagramofPerformanceConcepts ............136

8.3Amoreefficient perform function ................138

8.4PhraseAttributes .........................139

8.5Definitionofdefaultplayer defPlayer .............142

8.6DefinitionofPlayer fancyPlayer . ................147

9.1AnExampleofSelf-SimilarMusic

13.1VariousProbabilityDensityFunctions

14.1PartialDefinitionofthe Midi DataType

17.1SeveralSimpleMUIs .......................251

17.2MediatorsBetweentheContinuousandtheDiscrete .....253

17.3AChordBuilderMUI ......................259

18.1ASineWave ...........................267

18.2RMSAmplitudeforDifferentSignals ..............271

18.3Fletcher-MunsonEqualLoudnessContour ...........273

18.4SpectralPlotsofDifferentSignals ................275

18.5Time-VaryingSpectralPlots ...................277

18.6ChoiceofSamplingRate .....................279

18.7Aliasing1 .............................282

18.8Aliasing2 .............................283

18.9AProperlySampledSignal ...................285

18.10BlockDiagramofTypicalDigitalAudioSystem ........285

19.1Eutperea’sOscillators ......................295

19.2TableGeneratingFunctions ...................297

19.3ASimpleMelody .........................303

19.4ACompleteExampleofaSignal-FunctionBasedInstrument 304

19.5Envelopes .............................305

20.1ExamplesofFourierTransforms .................312

20.2GeneratingaSquareWavefromOddHarmonics .......313

20.3ComplexandPolarCoordinates .................317

20.4HelperCodeforPretty-PrintingDFTResults .........320

20.5AReal-TimeDisplayofFFTResults ..............326

21.1WorkingWithListsofSignalSources .............328

21.2ABellInstrument ........................329

21.3AMoreSophisticatedBellInstrument .............330

B.1StandardNumericClasses ....................357

ListofTables

10.1SomeUsefulPropertiesof map and fold

17.1MUIInput/OutputWidgets

17.2MUILayoutWidgetTransformers

Preface

In2000Iwroteabookcalled TheHaskellSchoolofExpression–Learning FunctionalProgramming throughMultimedia [Hud00].InthatbookIused graphics,animation,music,androboticsasawaytomotivatelearninghow toprogram,andspecificallyhowtolearn functionalprogramming using Haskell,apurelyfunctionalprogramminglanguage.Haskell[P+ 03]isquite abitdifferentfromconventionalimperativeorobject-orientedlanguages suchasC,C++,Java,C#,andsoon.Ittakesadifferentmind-setto programinsuchalanguage,andappealstothemathematicallyinclined andtothosewhoseekpurityandeleganceintheirprograms.Although Haskellwasdesignedovertwentyyearsago,ithasonlyrecentlybegunto catchoninasignificantway,notjustbecauseofitspurityandelegance, butbecausewithityoucansolvereal-worldproblemsquicklyandefficiently, andwithgreateconomyofcode.

Ihavealsohadalong,informal,yetpassionateinterestinmusic,being anamateurjazzpianistandhavingplayedinseveralbandsovertheyears. Aboutfifteenyearsago,inanefforttocombineworkwithplay,Iandmy studentswroteaHaskelllibrarycalled Haskore forexpressinghigh-level computermusicconceptsinapurelyfunctionalway[HMGW96 , Hud96, Hud03].Indeed,threeofthechaptersin TheHaskellSchoolofExpression summarizethebasicideasofthiswork.Soonafterthat,withthehelpof anotherstudent,IdesignedaHaskelllibrarycalled HasSound thatwas, essentially,aHaskellinterfaceto csound [Ver86]fordoingsoundsynthesis andinstrumentdesign.

Thus,whenIrecentlybecameresponsiblefortheMusicTrackinthe new ComputingandtheArts majoratYale,andbecameresponsiblefor teachingnotone,buttwocomputermusiccoursesinthenewcurriculum,it wasnaturaltobasethecoursematerialonHaskell.Thiscurrentbookisa rewriteof TheHaskellSchoolofExpression withafocusoncomputermusic, basedon,andgreatlyimprovingupon,theideasinHaskoreandHasSound.

ThenewHaskelllibrarythatincorporatesallofthisiscalled Euterpea. HaskellwasnamedafterthelogicianHaskellB.Currywho,alongwith AlonzoChurch,helpedestablishthetheoreticalfoundationsoffunctional programminginthe1940’s,whendigitalcomputersweremostlyjustagleam inresearchers’eyes.AcurioushistoricalfactisthatHaskellCurry’sfather, SamuelSilasCurry,helpedfoundanddirectaschoolinBostoncalledthe SchoolofExpression.(Thisschooleventuallyevolvedintowhatisnow Curry College.)Sincepurefunctionalprogrammingiscenteredaroundthenotion ofan expression,Ithoughtthat TheHaskellSchoolofExpression wouldbe agoodtitleformyfirstbook.Anditwasthusquitenaturaltochoose The HaskellSchoolofMusic formysecond!

HowToReadThisBook

Asmentionedearlier,thereisacertainmind-set,acertainviewpointofthe world,andacertainapproachtoproblemsolvingthatcollectivelyworkbest whenprogramminginHaskell(thisistrueforanyprogrammingparadigm). IfyouteachonlyHaskelllanguagedetailstoaCprogrammer,heorsheis likelytowriteugly,incomprehensiblefunctionalprograms.Butifyouteach howtothinkdifferently,howtoseeproblemsinadifferentlight,functional solutionswillcomeeasily,andelegantHaskellprogramswillresult.As SamuelSilasCurryoncesaid:

Allexpressioncomes fromwithinoutward,fromthecenterto thesurface,fromahiddensourcetooutwardmanifestation.The studyofexpressionasanaturalprocessbringsyouintocontact withcauseandmakesyoufeelthesourceofreality.

Whatisespeciallybeautifulaboutthisquoteisthatmusicisalsoaform ofexpression,althoughCurrywasmorelikelytalkingaboutwritingand speaking.Inaddition,ashasbeennotedbymany,musichasmanyties tomathematics.Soforme,combiningtheelegantmathematicalnatureof Haskellwiththatofmusicisasnaturalassinginganurserytune.

Usingahigh-levellanguagetoexpressmusicalideasis,ofcourse,not new.ButHaskellisuniqueinitsinsistenceonpurity(nosideeffects),and thisalonemakesitparticularlysuitableforexpressingmusicalideas.By focusingon what amusicalentityisratherthanon how tocreateit,weallow musicalideastotaketheirnaturalformasHaskellexpressions.Haskell’s manyabstractionmechanismsallowustowritecomputermusicprograms

thatareelegant,concise,yetpowerful.Wewillconsistentlyattempttolet themusicexpressitselfasnaturallyaspossible,withoutencodingitinterms ofirrelevantlanguagedetails.

Ofcourse,myultimategoalisnotjusttoteachcomputermusicconcepts. AlongthewayyouwillalsolearnHaskell.Thereisnolimittowhatone mightwishtodowithcomputermusic,andthereforethebetteryouare atprogramming,themoresuccessyouwillhave.ThisiswhyIthinkthat manylanguagesdesignedspecificallyforcomputermusic—althoughfunto workwith,easytouse,andcuteinconcept—facethedangerofbeingtoo limitedinexpressiveness.

Youdonotneedtoknowmuch,ifany,musictheorytoreadthisbook, andyoudonotneedtoplayaninstrument.Ofcourse,themoreyouknow aboutmusic,themoreyouwillbeabletoapplytheconceptslearnedinthis textinmusicallycreativeways.

Mygeneralapproachtointroducingcomputermusicconceptsistofirst provideanintuitiveexplanation,thenamathematicallyrigorousdefinition, andfinallyfullyexecutableHaskellcode.IntheprocessIintroduceHaskell featuresastheyareneeded,ratherthanallatonce.Ibelievethatthis interleavingofconceptsandapplicationsmakesthematerialeasiertodigest.

AnothercharacteristicofmyapproachisthatIdonothideanydetails—I wantEuterpeatobeastransparentaspossible!Therearenomagicalbuiltinoperations,nospecialcomputermusiccommandsorvalues.Thisworks outwellforseveralreasons.First,thereisinfactnothinguglyordifficult tohide—sowhyhideanythingatall?Second,byreadingthecode,youwill betterandmorequicklyunderstandHaskell.Finally,bysteppingthrough thedesignprocesswithme,youmaydecidethatyoupreferadifferent approach—thereis,afterall,noOneTrueWaytoexpresscomputermusic ideas.Iexpectthatthisprocesswillpositionyouwelltowriterich,creative musicalapplicationsonyourown.

Iencouragetheseasonedprogrammerhavingexperienceonlywithconventionalimperativeand/orobject-orientedlanguagestoreadthistextwith anopenmind.Manythingswillbedifferent,andwilllikelyfeelawkward. Therewillbeatendencytorelyonoldhabitswhenwritingnewprograms, andtoignoresuggestionsabouthowtoapproachthingsdifferently.Ifyou canmanagetoresistthosetendenciesIamconfidentthatyouwillhavean enjoyablelearningexperience.Thosewhosucceedinthisprocessoftenfind thatmanyideasaboutfunctionalprogrammingcanbeappliedtoimperativeandobject-orientedlanguagesaswell,andthattheirimperativecoding

xviii stylechangesforthebetter.

Ialsoasktheexperiencedprogrammertobepatientwhileintheearlier chaptersIexplainthingslike“syntax,”“operatorprecedence,”etc.,sinceit ismygoalthatthistextshouldbereadablebysomeonehavingonlymodest priorprogrammingexperience.Withpatiencethemoreadvancedideaswill appearsoonenough.

Ifyouareanoviceprogrammer,Isuggesttakingyourtimewiththe book;workthroughtheexercises,anddon’trushthings.If,however,you don’tfullygraspanidea,feelfreetomoveon,buttrytore-readdifficult materialatalatertimewhenyouhaveseenmoreexamplesoftheconcepts inaction.Forthemostpartthisisa“showbyexample”textbook,and youshouldtrytoexecuteasmanyoftheprogramsinthistextasyoucan, aswellaseveryprogramthatyouwrite.Learn-by-doingisthecorollaryto show-by-example.

Finally,Inotethatsomesectiontitlesareprefacedwiththeparenthetical phrase,“[Advanced]”.Thesesectionsmaybeskippeduponfirstreading, especiallyifthefocusisonlearningcomputermusicconcepts,asopposed toprogrammingconcepts.

HaskellImplementations

ThereareseveralimplementationsofHaskell,allavailablefreeontheInternetthroughtheHaskellusers’websiteat http://haskell.org.However, theonethathasdominatedallothers,andonwhichEuterpeaisbased, is GHC,aneasy-to-useandeasy-to-installHaskellcompilerandinterpreter (see http://haskell.org/ghc).GHCrunsonavarietyofplatforms,includingPC’s,variousflavorsofUnix,andMacs.Thepreferredwaytoinstall GHCisthroughthe HaskellPlatform (http://hackage.haskell.org/platform/). Anytexteditorcanbeusedtocreatesourcefiles,butIprefertouseemacs (see http://www.gnu.org/software/emacs),alongwithitsHaskellmode (see http://projects.haskell.org/haskellmode-emacs/).Theentire Euterpealibrary,includingthesourcecodefromthistextbook,andinstallationinstructions,canbefoundat http://haskell.cs.yale.edu

Acknowledgements

Iwishtothankmyfundingagencies—theNationalScienceFoundation, theDefenseAdvancedResearchProjectsAgency,andMicrosoftResearch— fortheirgeneroussupportofresearchthatcontributedtothefoundations ofEuterpea.YaleUniversityhasprovidedmeastimulatingandflexible environmenttopursuemydreamsforoverthirtyyears,andIamespecially thankfulforitsrecentsupportoftheComputingandtheArtsinitiative.

TomMakucevich,atalentedcomputermusicpractitionerandcomposer inNewHaven,wastheoriginalmotivator,andfirstuser,ofHaskore,which precededEuterpea.Watchinghimtoilendlesslywithlow-levelcsoundprogramswassimplytoomuchformetobear!Severalundergraduatestudents atYalecontributedtotheoriginaldesignandimplementationofHaskore.I wouldliketothankinparticularthecontributionsofSyamGaddeandBo Whong,whoco-authoredtheoriginalpaperonHaskore.Additionally,Matt ZamechelpedmegreatlyinthecreationofHasSound.

Iwishtothankmymorerecentgraduatestudents,inparticularHai (Paul)Liu,EricCheng,DonyaQuick,andDanielWinograd-Cortfortheir helpinwritingmuchofthecodethatconstitutesthecurrentEuterpealibrary.Inaddition,manystudentsinmycomputermusicclassesatYale providedvaluablefeedbackthroughearlierdraftsofthemanuscript.

Finally,Iwishtothankmywife,CathyVanDyke,mybestfriendand ardentsupporter,whoselove,patience,andunderstandinghavehelpedme getthroughsomebadtimes,andenjoythegood.

HappyHaskellMusicMaking!

PaulHudak

NewHaven January2012

Chapter1 OverviewofComputer Music,Euterpea,andHaskell

Computersareeverywhere.Andsoismusic!Althoughsomemightthink ofthetwoasbeingatbestdistantrelatives,infacttheysharemanydeep properties.Musiccomesfromthesoul,andisinspiredbytheheart,yetit hasthemathematicalrigorofcomputers.Computershavemathematical rigorofcourse,yetthemostcreativeideasinmathematicsandcomputer sciencecomefromthesoul,justlikemusic.Bothdisciplinesdemandboth left-brainandright-brainskills.Italwayssurprisesmehowmanycomputer scientistsandmathematicianshaveaseriousinterestinmusic.Itseems thatthosewithastrongaffinityoracuityinoneofthesedisciplinesisoften strongintheotheraswell.

Itisquitenaturalthentoconsiderhowthetwomightinteract.In factthereisalonghistoryofinteractionsbetweenmusicandmathematics, datingbacktotheGreeks’constructionofmusicalscalesbasedonarithmetic relationships,andincludingmanyclassicalcomposersuseofmathematical structures,theformalharmonicanalysisofmusic,andmanymodernmusic compositiontechniques.Advancedmusictheoryusesideasfromdiverse branchesofmathematicssuchasnumbertheory,abstractalgebra,topology, categorytheory,calculus,andsoon.

Thereisalsoalonghistoryofeffortstocombinecomputersandmusic. Mostconsumerelectronicstodayaredigital,asaremostformsofaudioprocessingandrecording.Butinaddition,digitalmusicalinstrumentsprovide newmodesofexpression,notationsoftwareandsequencershavebecome standardtoolsfortheworkingmusician,andthosewiththemostcomputer

CHAPTER1.COMPUTERMUSIC,EUTERPEA,ANDHASKELL 2

sciencesavvyusecomputerstoexplorenewmodesofcomposition,transformation,performance,andanalysis.

Thistextbookexploresthefundamentalsofcomputermusicusinga language-centricapproach.Inparticular,thefunctionalprogramminglanguage Haskell isusedtoexpressallofthecomputermusicconcepts.Thus aby-productoflearningcomputermusicconceptswillbelearninghowto programinHaskell.ThecoremusicalideasarecollectedintoaHaskelllibrarycalled Euterpea.Thename“Euterpea”isderivedfrom Euterpe,who wasoneofthenineGreekmuses,orgoddessesofthearts,specificallythe museofmusic.AhypotheticalpictureofEuterpegracesthecoverofthis textbook.

1.1TheNotevs.SignalDichotomy

Thefieldofcomputermusichasgrownastronomicallyoverthepastseveral decades,andthematerialcanbestructuredandorganizedalongseveral dimensions.Adimensionthatprovesparticularyusefulwithrespecttoa programminglanguageisonethatseparates high-level musicalconcernsfrom low-level musicalconcerns.Sincea“high-level”programminglanguage— namelyHaskell—isusedtoprogramatbothofthesemusicallevels,toavoid confusiontheterms notelevel and signallevel willbeusedinthemusical dimension.

Atthe notelevel,a note (i.e.pitchandduration)isthelowestmusical entitythatisconsidered,andeverythingelseisbuiltupfromthere.Atthis level,inadditiontoconventionalrepresentationsofmusic,wecanstudyinterestingaspectsofso-called algorithmiccomposition,includingtheuseof fractals,grammar-basedsystems,stochasticprocesses,andsoon.Fromthis basiswecanalsostudytheharmonicandrhythmic analysis ofmusic,althoughthatisnotcurrentlyanemphasisinthistextbook.Haskellfacilitates programmingatthislevelthroughitspowerfuldataabstractionfacilities, higher-orderfunctions,anddeclarativesemantics.

Incontrast,atthe signallevel thefocusisontheactualsoundgenerated inacomputermusicapplication,andthusa signal isthelowestentitythat isconsidered.Soundisconcretelyrepresentedinadigitalcomputerbya discretesamplingofthecontinuousaudiosignal,atahighenoughratethat humanearscannotdistinguishthediscretefromthecontinuous,usually 44,100samplespersecond(thestandardsamplingrateusedforCDs,mp3 files,andsoon).ButinEuterpea,thesedetailsarehidden:signalsare

CHAPTER1.COMPUTERMUSIC,EUTERPEA,ANDHASKELL 3

treatedabstractlyascontinuousquantities.Thisgreatlyeasestheburden ofprogrammingwithsequencesofdiscretevalues.Atthesignallevel,wecan studysoundsynthesistechniques(tosimulatethesoundofaconventional instrument,say,orsomethingcompletelyartificial),audioprocessing(e.g. determiningthefrequencyspectrumofasignal),andspecialeffects(reverb, panning,distortion,andsoon).

Supposeforamomentthatamusicianisplayingmusicusingametronome setat96,whichcorrespondsto96beatsperminute.Thatmeansthatone beattakes 60/96 =0.625seconds.Atastereosamplingrateof44,100samples persecond,thatinturntranslatesinto2 × 0 625 × 44, 100=55,125samples,andeachsampletypicallyoccupiesseveralbytesofcomputermemory. Thisistypicaloftheminimummemoryrequirementsofacomputationat thesignallevel.Incontrast,atthenotelevel,weonlyneedsomekindof operatorordatastructurethatsays“playthisnote,”whichrequiresatotal ofonlyasmallhandfulofbytes.Thisdramaticdifferencehighlightsoneof thekeycomputationaldifferencesbetweenprogrammingatthenotelevel versusthesignallevel.

Ofcourse,manycomputermusicapplicationsinvolveboththenotelevel and thesignallevel,andindeedthereneedstobeamechanismtomediate betweenthetwo.Althoughsuchmediationcantakemanyforms,itisfor themostpartstraightforward.Whichisanotherreasonwhythedistinction betweenthenotelevelandthesignallevelissonatural.

Thistextbookbeginswithatreatmentofthenotelevel(Chapters 1-17) andfollowswithatreatmentofthesignallevel(Chapters 18-21).Ifyouare interestedonlyinthesignallevel,youcouldskipChapters 8-17 .

1.2BasicPrinciplesofProgramming

Programming,initsbroadestsense,is problemsolving.Itbeginsbyrecognizingproblemsthatcanandshouldbesolvedusingadigitalcomputer. Thusthefirststepinprogrammingisansweringthequestion,“WhatproblemamItryingtosolve?”

Oncetheproblemisunderstood,asolutionmustbefound.Thismay notbeeasy,ofcourse,andinfactyoumaydiscoverseveralsolutions,soa waytomeasuresuccessisneeded.Therearevariousdimensionsinwhichto dothis,includingcorrectness(“WillIgettherightanswer?”)andefficiency (“Willitrunfastenough,orusetoomuchmemory?”).Butthedistinctionof whichsolutionisbetterisnotalwaysclear,sincethenumberofdimensions

CHAPTER1.COMPUTERMUSIC,EUTERPEA,ANDHASKELL 4

canbelarge,andprogramswilloftenexcelinonedimensionanddopoorly inothers.Forexample,theremaybeonesolutionthatisfastest,onethat usestheleastamountofmemory,andonethatiseasiesttounderstand. Decidingwhichtochoosecanbedifficult,andisoneofthemoreinteresting challengesinprogramming.

Thelastmeasureofsuccessmentionedabove—clarityofaprogram— issomewhatelusive:difficulttoquantifyandmeasure.Nevertheless,in largesoftwaresystemsclarityisanespeciallyimportantgoal,sincesuch systemsareworkedonbymanypeopleoverlongperiodsoftime,andevolve considerablyastheymature.Havingeasy-to-understandcodemakesitmuch easiertomodify.

Intheareaofcomputermusic,thereisanotherreasonwhyclarityis important:namely,thatthecodeoftenrepresentstheauthor’sthought process,musicalintent,andartisticchoices.Aconventionalmusicalscore doesnotsaymuchaboutwhatthecomposerthoughtasshewrotethemusic, butaprogramoftendoes.Sowhenyouwriteyourprograms,writethemfor otherstosee,andaimforeleganceandbeauty,justlikethemusicalresult thatyoudesire.

Programmingisitselfacreativeprocess.Sometimesprogrammingsolutions(orartisticcreations)cometomindallatonce,withlittleeffort. Moreoften,however,theyarediscoveredonlyafterlotsofhardwork!We maywriteaprogram,modifyit,throwitawayandstartover,giveup,start again,andsoon.Itisimportanttorealizethatsuchhardworkandreworkingofprogramsisthenorm,andinfactyouareencouragedtogetintothe habitofdoingso.Donotalwaysbesatisfiedwithyourfirstsolution,and alwaysbepreparedtogobackandchangeoreventhrowawaythoseparts ofyourprogramthatyouarenothappywith.

1.3ComputationbyCalculation

Itishelpfulwhenlearninganewprogramminglanguagetohaveagood graspofhowprogramsinthatlanguageareexecuted—inotherwords,an understandingofwhataprogram means.TheexecutionofHaskellprograms isperhapsbestunderstoodas computationbycalculation.Programsin Haskellcanbeviewedas functions whoseinputisthatoftheproblembeing solved,andwhoseoutputisthedesiredresult—andthebehavioroffunctions canbeeffectivelyunderstoodascomputationbycalculation.

Anexampleinvolvingnumbersmighthelptodemonstratetheseideas.

CHAPTER1.COMPUTERMUSIC,EUTERPEA,ANDHASKELL 5

Numbersareusedinmanyapplications,andcomputermusicisnoexception. Forexample,integersmightbeusedtorepresentpitch,andfloating-point numbersmightbeusedtoperformcalculationsinvolvingfrequencyoramplitude.

Supposewewishtoperformanarithmeticcalculationsuchas3 × (9+5). InHaskellthiswouldbewrittenas3 ∗ (9+5),sincemoststandardcomputer keyboardsandtexteditorsdonotrecognizethespecialsymbol ×.Theresult canbecalculatedasfollows:

3 ∗ (9+5)

⇒ 3 ∗ 14 ⇒ 42

Itturnsoutthatthisisnottheonlywaytocomputetheresult,asevidenced bythisalternativecalculation:1

3 ∗ (9+5)

⇒ 3 ∗ 9+3 ∗ 5 ⇒ 27+3 ∗ 5

27+15 ⇒ 42

Eventhoughthiscalculationtakestwoextrasteps,itatleastgivesthe same,correctanswer.Indeed,animportantpropertyofeachandevery programwritteninHaskellisthatitwillalwaysyieldthesameanswer whengiventhesameinputs,regardlessoftheorderchosentoperformthe calculations.2 Thisispreciselythemathematicaldefinitionofa function : forthesameinputs,italwaysyieldsthesameoutput.

Ontheotherhand,thefirstcalculationaboverequiredfewerstepsthan thesecond,andthusitissaidtobemore efficient.Efficiencyinbothspace (amountofmemoryused)andtime(numberofstepsexecuted)isimportant whensearchingforsolutionstoproblems.Ofcourse,ifthecomputation returnsthewronganswer,efficiencyisamootpoint.Ingeneralitisbest tosearchfirstforanelegant(andcorrect!)solutiontoaproblem,andlater refineitforbetterperformance.Thisstrategyissometimessummarizedas, “Getitrightfirst!”

Theabovecalculationsarefairlytrivial,butmuchmoresophisticated computationswillbeintroducedsoonenough.Forstarters—andtointro-

1 Thisassumesthatmultiplicationdistributesoveradditioninthenumbersystembeing used,apointthatwillbereturnedtolaterinthetext.

2 Thisistrueaslongasanon-terminatingsequenceofcalculationsisnotchosen,another issuethatwillbeaddressedlater.

CHAPTER1.COMPUTERMUSIC,EUTERPEA,ANDHASKELL 6

ducetheideaofaHaskellfunction—thearithmeticoperationsperformedin thepreviousexamplecanbe generalized bydefiningafunctiontoperform themforanynumbers x , y ,and z :

simplexyz = x ∗ (y + z )

Thisequationdefines simple asafunctionofthree arguments, x , y ,and z Inmathematicalnotationthisdefinitionmightbewrittendifferently,such asoneofthefollowing:

simple (x,y,z )= x × (y + z )

simple (x,y,z )= x · (y + z )

simple (x,y,z )= x(y + z )

Inanycase,itshouldbeclearthat“simple 395”isthesameas“3 ∗ (9+5).” Infacttheproperwaytocalculatetheresultis:

simple 395 ⇒ 3 ∗ (9+5) ⇒ 3 ∗ 14 ⇒ 42

Thefirststepinthiscalculationisanexampleof unfolding afunction definition:3issubstitutedfor x ,9for y ,and5for z ontheright-handside ofthedefinitionof simple .Thisisanentirelymechanicalprocess,notunlike whatthecomputeractuallydoestoexecutetheprogram.

simple 395issaidto evaluate to42.Toexpressthefactthatan expression e evaluates(viazero,one,orpossiblymanymoresteps)tothe value v ,wewillwrite e =⇒ v (thisarrowislongerthanthatusedearlier). Sowecansaydirectly,forexample,that simple 395=⇒ 42,whichshould beread“simple 395evaluatesto42.”

With simple nowsuitablydefined,wecanrepeatthesequenceofarithmeticcalculationsasoftenaswelike,usingdifferentvaluesforthearguments to simple .Forexample, simple 432=⇒ 20.

Wecanalsousecalculationto proveproperties aboutprograms.For example,itshouldbeclearthatforany a , b ,and c , simpleabc should yieldthesameresultas simpleacb .Foraproofofthis,wecalculate symbolically ;thatis,usingthesymbols a , b ,and c ratherthanconcrete numberssuchas3,5,and9:

simpleabc

⇒ a ∗ (b + c )

⇒ a ∗ (c + b ) ⇒ simpleacb

Notethatthesamenotationisusedforthesesymbolicstepsasforconcrete ones.Inparticular,thearrowinthenotationreflectsthedirectionofformal reasoning,andnothingmore.Ingeneral,if e1 ⇒ e2 ,thenitisalsotruethat e2 ⇒ e1 .

Thesesymbolicstepsarealsoreferredtoasas“calculations,”even thoughthecomputerwillnottypicallyperformthemwhenexecutingaprogram(althoughitmightperformthem before aprogramisrunifitthinks thatitmightmaketheprogramrunfaster).Thesecondstepinthecalculationabovereliesonthecommutativityofaddition(namelythat,forany numbers x and y , x + y = y + x).Thethirdstepisthereverseofanunfold step,andisappropriatelycalleda fold calculation.Itwouldbeparticularlystrangeifacomputerperformedthisstepwhileexecutingaprogram, sinceitdoesnotseemtobeheadedtowardafinalanswer.Butforproving propertiesaboutprograms,such“backwardreasoning”isquiteimportant.

Whenwewishtospelloutthejustificationforeachstep,whethersymbolicorconcrete,acalculationcanbeannotatedwithmoredetail,asin: simpleabc

⇒{ unfold }

a ∗ (b + c )

⇒{ commutativity } a ∗ (c + b ) ⇒{ fold } simpleacb

Inmostcases,however,thiswillnotbenecessary.

Provingpropertiesofprogramsisanotherthemethatwillberepeated ofteninthistext.Computermusicapplicationsoftenhavesomekindofa mathematicalbasis,andthatmathematicsmustbereflectedsomewherein ourprograms.Buthowdoweknowifwegotitright?Proofbycalculation isonewaytoconnecttheproblemspecificationwiththeprogramsolution.

Morebroadlyspeaking,astheworldbeginstorelymoreandmoreon computerstoaccomplishnotjustordinarytaskssuchaswritingtermpapers,sendingemail,andsocialnetworking,butalsolife-criticaltaskssuch ascontrollingmedicalproceduresandguidingspacecraft,thenthecorrectnessofprogramsgainsinimportance.Provingcomplexpropertiesoflarge, complexprogramsisnoteasy—andrarelyifeverdoneinpractice—butthat shouldnotdeterusfromprovingsimplerpropertiesofthewholesystem,or complexpropertiesofpartsofthesystem,sincesuchproofsmayuncover errors,andifnot,willatleastgiveusconfidenceinoureffort.

Ifyouaresomeonewhoisalreadyanexperiencedprogrammer,theidea ofcomputing everything bycalculationmayseemoddatbest,andna¨ıveat worst.Howdowewritetoafile,playasound,drawapicture,orrespond tomouse-clicks?Ifyouarewonderingaboutthesethings,itishopedthat youhavepatiencereadingtheearlychapters,andthatyoufinddelightin readingthelaterchapterswherethefullpowerofthisapproachbeginsto shine.

Inmanywaysthisfirstchapteristhemostdifficult,sinceitcontainsthe highestdensityofnewconcepts.Ifthereaderhastroublewithsomeofthe conceptsinthisoverviewchapter,keepinmindthatmostofthemwillbe revisitedinlaterchapters.Anddonothesitatetoreturntothischapter latertore-readdifficultsections;theywilllikelybemucheasiertograspat thattime.

Details: Intheremainderofthistextbooktheneedwilloftenarisetoexplain someaspectofHaskellinmoredetail,withoutdistractingtoomuchfromthe primarylineofdiscourse.Inthosecircumstancestheexplanationswillbeoffsetin ashadedboxsuchasthisone,proceededwiththeword“Details.”

Exercise1.1 Writeoutallofthestepsinthecalculationofthevalueof simple (simple 234)56

Exercise1.2 Provebycalculationthat simple (a b ) ab =⇒ a2 b2

1.4ExpressionsandValues

InHaskell,theentitiesonwhichcalculationsareperformedarecalled expressions,andtheentitiesthatresultfromacalculation—i.e.“theanswers”—are called values.Itishelpfultothinkofavaluejustasanexpressiononwhich nomorecalculationcanbecarriedout—everyvalueisanexpression,but nottheotherwayaround.

Examplesofexpressionsinclude atomic (meaning,indivisible)values suchastheinteger42andthecharacter ’a’,whichareexamplesoftwo primitive atomicvaluesinHaskell.Thenextchapterintroducesexamples

CHAPTER1.COMPUTERMUSIC,EUTERPEA,ANDHASKELL 9

of constructor atomicvalues,suchasthemusicalnotes C , D , Ef , Fs ,etc., whichinstandardmusicnotationarewrittenC,D,E ,F ,etc.,andare pronouncedC,D,E-flat,F-sharp,etc.(Inmusictheory,notenamesare called pitchclasses.).

Inaddition,thereare structured expressions(i.e.,madefromsmaller pieces)suchasthe list ofpitches[ C , D , Ef ],thecharacter/number pair (’b’, 4)(listsandpairsaredifferentinasubtleway,tobedescribedlater), andthestring "Euterpea".Eachofthesestructuredexpressionsisalsoa value,sincebythemselvesthereisnofurthercalculationthatcanbecarried out.Asanotherexample,1+2isanexpression,andonestepofcalculation yieldstheexpression3,whichisavalue,sincenomorecalculationscan beperformed.Asafinalexample,aswasexpainedearlier,theexpression simple 395evaluatestothevalue42.

Sometimes,however,anexpressionhasonlyanever-endingsequenceof calculations.Forexample,if x isdefinedas:

x = x +1 thenhereiswhathappenswhentryingtocalculatethevalueof x :

x

⇒ x +1

⇒ (x +1)+1

⇒ ((x +1)+1)+1

⇒ (((x +1)+1)+1)+1

Similarly,ifafunction f isdefinedas:

fx = f (x 1) thenanexpressionsuchas f 42runsintoasimilarproblem: f 42

⇒ f 41

⇒ f 40

⇒ f 39 ...

Bothoftheseclearlyresultinanever-endingsequenceofcalculations.Such expressionsaresaidtonotterminate,or diverge.Insuchcasesthesymbol ⊥,pronounced“bottom,”isusedtodenotethevalueoftheexpression. ThismeansthateverydivergingcomputationinHaskelldenotesthesame

Another random document with no related content on Scribd:

This eBook is for the use of anyone anywhere in the United States and most other parts of the world at no cost and with almost no restrictions whatsoever. You may copy it, give it away or re-use it under the terms of the Project Gutenberg License included with this eBook or online at www.gutenberg.org. If you are not located in the United States, you will have to check the laws of the country where you are located before using this eBook.

1.E.2. If an individual Project Gutenberg™ electronic work is derived from texts not protected by U.S. copyright law (does not contain a notice indicating that it is posted with permission of the copyright holder), the work can be copied and distributed to anyone in the United States without paying any fees or charges. If you are redistributing or providing access to a work with the phrase “Project Gutenberg” associated with or appearing on the work, you must comply either with the requirements of paragraphs 1.E.1 through 1.E.7 or obtain permission for the use of the work and the Project Gutenberg™ trademark as set forth in paragraphs 1.E.8 or 1.E.9.

1.E.3. If an individual Project Gutenberg™ electronic work is posted with the permission of the copyright holder, your use and distribution must comply with both paragraphs 1.E.1 through 1.E.7 and any additional terms imposed by the copyright holder. Additional terms will be linked to the Project Gutenberg™ License for all works posted with the permission of the copyright holder found at the beginning of this work.

1.E.4. Do not unlink or detach or remove the full Project Gutenberg™ License terms from this work, or any files containing a part of this work or any other work associated with Project Gutenberg™.

1.E.5. Do not copy, display, perform, distribute or redistribute this electronic work, or any part of this electronic work, without prominently displaying the sentence set forth in paragraph 1.E.1 with active links or immediate access to the full terms of the Project Gutenberg™ License.

1.E.6. You may convert to and distribute this work in any binary, compressed, marked up, nonproprietary or proprietary form, including any word processing or hypertext form. However, if you provide access to or distribute copies of a Project Gutenberg™ work in a format other than “Plain Vanilla ASCII” or other format used in the official version posted on the official Project Gutenberg™ website (www.gutenberg.org), you must, at no additional cost, fee or expense to the user, provide a copy, a means of exporting a copy, or a means of obtaining a copy upon request, of the work in its original “Plain Vanilla ASCII” or other form. Any alternate format must include the full Project Gutenberg™ License as specified in paragraph 1.E.1.

1.E.7. Do not charge a fee for access to, viewing, displaying, performing, copying or distributing any Project Gutenberg™ works unless you comply with paragraph 1.E.8 or 1.E.9.

1.E.8. You may charge a reasonable fee for copies of or providing access to or distributing Project Gutenberg™ electronic works provided that:

• You pay a royalty fee of 20% of the gross profits you derive from the use of Project Gutenberg™ works calculated using the method you already use to calculate your applicable taxes. The fee is owed to the owner of the Project Gutenberg™ trademark, but he has agreed to donate royalties under this paragraph to the Project Gutenberg Literary Archive Foundation. Royalty payments must be paid within 60 days following each date on which you prepare (or are legally required to prepare) your periodic tax returns. Royalty payments should be clearly marked as such and sent to the Project Gutenberg Literary Archive Foundation at the address specified in Section 4, “Information about donations to the Project Gutenberg Literary Archive Foundation.”

• You provide a full refund of any money paid by a user who notifies you in writing (or by e-mail) within 30 days of receipt that s/he does not agree to the terms of the full Project Gutenberg™

License. You must require such a user to return or destroy all copies of the works possessed in a physical medium and discontinue all use of and all access to other copies of Project Gutenberg™ works.

• You provide, in accordance with paragraph 1.F.3, a full refund of any money paid for a work or a replacement copy, if a defect in the electronic work is discovered and reported to you within 90 days of receipt of the work.

• You comply with all other terms of this agreement for free distribution of Project Gutenberg™ works.

1.E.9. If you wish to charge a fee or distribute a Project Gutenberg™ electronic work or group of works on different terms than are set forth in this agreement, you must obtain permission in writing from the Project Gutenberg Literary Archive Foundation, the manager of the Project Gutenberg™ trademark. Contact the Foundation as set forth in Section 3 below

1.F.

1.F.1. Project Gutenberg volunteers and employees expend considerable effort to identify, do copyright research on, transcribe and proofread works not protected by U.S. copyright law in creating the Project Gutenberg™ collection. Despite these efforts, Project Gutenberg™ electronic works, and the medium on which they may be stored, may contain “Defects,” such as, but not limited to, incomplete, inaccurate or corrupt data, transcription errors, a copyright or other intellectual property infringement, a defective or damaged disk or other medium, a computer virus, or computer codes that damage or cannot be read by your equipment.

1.F.2. LIMITED WARRANTY,

DISCLAIMER OF DAMAGES

- Except for the “Right of Replacement or Refund” described in paragraph 1.F.3, the Project Gutenberg Literary Archive Foundation, the owner of the Project Gutenberg™ trademark, and any other party

distributing a Project Gutenberg™ electronic work under this agreement, disclaim all liability to you for damages, costs and expenses, including legal fees. YOU AGREE THAT YOU HAVE NO REMEDIES FOR NEGLIGENCE, STRICT LIABILITY, BREACH OF WARRANTY OR BREACH OF CONTRACT EXCEPT THOSE PROVIDED IN PARAGRAPH 1.F.3. YOU AGREE THAT THE FOUNDATION, THE TRADEMARK OWNER, AND ANY DISTRIBUTOR UNDER THIS AGREEMENT WILL NOT BE LIABLE TO YOU FOR ACTUAL, DIRECT, INDIRECT, CONSEQUENTIAL, PUNITIVE OR INCIDENTAL DAMAGES EVEN IF YOU GIVE NOTICE OF THE POSSIBILITY OF SUCH DAMAGE.

1.F.3. LIMITED RIGHT OF REPLACEMENT OR REFUND - If you discover a defect in this electronic work within 90 days of receiving it, you can receive a refund of the money (if any) you paid for it by sending a written explanation to the person you received the work from. If you received the work on a physical medium, you must return the medium with your written explanation. The person or entity that provided you with the defective work may elect to provide a replacement copy in lieu of a refund. If you received the work electronically, the person or entity providing it to you may choose to give you a second opportunity to receive the work electronically in lieu of a refund. If the second copy is also defective, you may demand a refund in writing without further opportunities to fix the problem.

1.F.4. Except for the limited right of replacement or refund set forth in paragraph 1.F.3, this work is provided to you ‘AS-IS’, WITH NO OTHER WARRANTIES OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY OR FITNESS FOR ANY PURPOSE.

1.F.5. Some states do not allow disclaimers of certain implied warranties or the exclusion or limitation of certain types of damages. If any disclaimer or limitation set forth in this agreement violates the law of the state applicable to this agreement, the agreement shall be interpreted to make the maximum disclaimer or limitation permitted

by the applicable state law. The invalidity or unenforceability of any provision of this agreement shall not void the remaining provisions.

1.F.6.

INDEMNITY

- You agree to indemnify and hold the Foundation, the trademark owner, any agent or employee of the Foundation, anyone providing copies of Project Gutenberg™ electronic works in accordance with this agreement, and any volunteers associated with the production, promotion and distribution of Project Gutenberg™ electronic works, harmless from all liability, costs and expenses, including legal fees, that arise directly or indirectly from any of the following which you do or cause to occur: (a) distribution of this or any Project Gutenberg™ work, (b) alteration, modification, or additions or deletions to any Project Gutenberg™ work, and (c) any Defect you cause.

Section 2. Information about the Mission of Project Gutenberg™

Project Gutenberg™ is synonymous with the free distribution of electronic works in formats readable by the widest variety of computers including obsolete, old, middle-aged and new computers. It exists because of the efforts of hundreds of volunteers and donations from people in all walks of life.

Volunteers and financial support to provide volunteers with the assistance they need are critical to reaching Project Gutenberg™’s goals and ensuring that the Project Gutenberg™ collection will remain freely available for generations to come. In 2001, the Project Gutenberg Literary Archive Foundation was created to provide a secure and permanent future for Project Gutenberg™ and future generations. To learn more about the Project Gutenberg Literary Archive Foundation and how your efforts and donations can help, see Sections 3 and 4 and the Foundation information page at www.gutenberg.org.

Section 3. Information about the Project

Gutenberg

Literary Archive Foundation

The Project Gutenberg Literary Archive Foundation is a non-profit 501(c)(3) educational corporation organized under the laws of the state of Mississippi and granted tax exempt status by the Internal Revenue Service. The Foundation’s EIN or federal tax identification number is 64-6221541. Contributions to the Project Gutenberg Literary Archive Foundation are tax deductible to the full extent permitted by U.S. federal laws and your state’s laws.

The Foundation’s business office is located at 809 North 1500 West, Salt Lake City, UT 84116, (801) 596-1887. Email contact links and up to date contact information can be found at the Foundation’s website and official page at www.gutenberg.org/contact

Section 4. Information about Donations to the Project Gutenberg Literary Archive Foundation

Project Gutenberg™ depends upon and cannot survive without widespread public support and donations to carry out its mission of increasing the number of public domain and licensed works that can be freely distributed in machine-readable form accessible by the widest array of equipment including outdated equipment. Many small donations ($1 to $5,000) are particularly important to maintaining tax exempt status with the IRS.

The Foundation is committed to complying with the laws regulating charities and charitable donations in all 50 states of the United States. Compliance requirements are not uniform and it takes a considerable effort, much paperwork and many fees to meet and keep up with these requirements. We do not solicit donations in locations where we have not received written confirmation of

compliance. To SEND DONATIONS or determine the status of compliance for any particular state visit www.gutenberg.org/donate.

While we cannot and do not solicit contributions from states where we have not met the solicitation requirements, we know of no prohibition against accepting unsolicited donations from donors in such states who approach us with offers to donate.

International donations are gratefully accepted, but we cannot make any statements concerning tax treatment of donations received from outside the United States. U.S. laws alone swamp our small staff.

Please check the Project Gutenberg web pages for current donation methods and addresses. Donations are accepted in a number of other ways including checks, online payments and credit card donations. To donate, please visit: www.gutenberg.org/donate.

Section 5. General Information About Project Gutenberg™ electronic works

Professor Michael S. Hart was the originator of the Project Gutenberg™ concept of a library of electronic works that could be freely shared with anyone. For forty years, he produced and distributed Project Gutenberg™ eBooks with only a loose network of volunteer support.

Project Gutenberg™ eBooks are often created from several printed editions, all of which are confirmed as not protected by copyright in the U.S. unless a copyright notice is included. Thus, we do not necessarily keep eBooks in compliance with any particular paper edition.

Most people start at our website which has the main PG search facility: www.gutenberg.org.

This website includes information about Project Gutenberg™, including how to make donations to the Project Gutenberg Literary

Archive Foundation, how to help produce our new eBooks, and how to subscribe to our email newsletter to hear about new eBooks.

Turn static files into dynamic content formats.

Create a flipbook
Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.