Sie sind auf Seite 1von 26

SeminarReportOn

FUNCTIONALPROGRAMMINGINHASKELL
Submittedby

SITHARAA
Inthepartialfulfillmentofrequirementsindegreeof MasterofTechnology(MTech)inComputer&InformationScience

DEPARTMENTOFCOMPUTERSCIENCE COCHINUNIVERSITYOFSCIENCEANDTECHNOLOGY KOCHI682022 2008

ACKNOWLEDGEMENT

IthankGodalmightyforguidingmethroughouttheseminar.Iwouldliketothankallthosewho havecontributedtothecompletionoftheseminarandhelpedmewithvaluablesuggestionsfor improvement. IamextremelygratefultoProf.Dr.KPouloseJacob,Director,Dept.ofComputerScience,for providing me with best facilities and atmosphere for the creative work guidance and encouragement.Iwouldliketothankmycoordinator,Mr.GSanthoshKumar,Lecturer,Dept.of computerScience,forallhelpandsupportextendtome.Ithankallstaffmembersofmycollege andfriendsforextendingtheircooperationduringmyseminar. AboveallIwouldliketothankmyparentswithoutwhoseblessings;Iwouldnothavebeenableto accomplishmygoal.

ABSTRACT

Assoftwarebecomesmoreandmorecomplex,itismoreandmoreimportanttostructureitwell. Wellstructuredsoftwareiseasytowrite,easytodebug,andprovidesacollectionofmodulesthat canbereusedtoreducefutureprogrammingcosts.Conventionallanguagesplaceconceptuallimits onthewayproblemscanbemodularized.Functionallanguagespushthoselimitsback.Writing largesoftwaresystemsthatworkisdifficultandexpensive.Maintainingthosesystemsisevenmore difficultandexpensive.Functionalprogramminglanguages,suchasHaskell,canmakeiteasierand cheaper. Haskellisanadvancedpurelyfunctionalprogramminglanguage.Theproductofmorethantwenty yearsofcuttingedgeresearch,itallowsrapiddevelopmentofrobust,concise,correctsoftware.With strong support for integration with other languages, builtin concurrency and parallelism, debuggers,profilers, richlibraries andanactivecommunity,Haskellmakesiteasiertoproduce flexible,maintainablehighqualitysoftware.

KEYWORDS: lambdacalculus,pure,currying,lazyevaluation,higherorderfunctions,Lolita, house,listcomprehension,tailrecursion,adhocpolymorphism.

CONTENTS

1.INTRODUCTION.........................................................................................................5 2.FUNCTIONALvs.IMPERATIVEPROGRAMMING...............................................6 3.FEATURESOFHASKELL.........................................................................................7 3.1PURE...................................................................................................................7 3.2STRONGLYTYPED...........................................................................................7 3.3STATICALLYTYPED........................................................................................8 3.4FUNCTIONAL....................................................................................................8 3.5CURRYING.........................................................................................................10 3.6LISTCOMPREHENSIONS................................................................................10 3.7LAZYEVALUATION.......................................................................................12 3.8RECURSION................................................................................................14 3.9HIGHERORDERFUNCTIONS..................................................................15 3.10POLYMORPHISM.....................................................................................................16 4.APPLICATIONAREAS.....................................................................................................18 4.1NATURALLANGUAGEINTERFACES.......................................................22 4.2PARALLELPROGRAMMING.......................................................................23 5.HASKELLINPRACTICE........................................................................................24 6.CONCLUSION...........................................................................................................25 7.REFERENCES............................................................................................................26

1.INTRODUCTION
Haskellisacomputerprogramminglanguage.Inparticular,itisapolymorphicallystaticallytyped, lazy, purely functional language, quite different from most other programming languages. The language is named for Haskell Brooks Curry, whose work in mathematical logic serves as a foundationforfunctionallanguages.Haskellisbasedonthelambdacalculus;hencethelambdais usedaslogo.Haskelloffers:

Substantiallyincreasedprogrammerproductivity. Shorter,clearer,andmoremaintainablecode. Fewererrors,higherreliability. Asmaller"semanticgap"betweentheprogrammerandthelanguage. Shorterleadtimes.

Haskellisawidespectrumlanguage,suitableforavarietyofapplications.Itisparticularlysuitable forprogramswhichneedtobehighlymodifiableandmaintainable.Muchofasoftwareproduct's life is spent in specification, design and maintenance, and not in programming. Functional languagesaresuperbforwritingspecificationswhichcanactuallybeexecutedandhencetestedand debugged.Suchaspecificationthenisthefirstprototypeofthefinalprogram.Functionalprograms arealsorelativelyeasytomaintain,becausethecodeisshorter,clearer,andtherigorouscontrolof sideeffectseliminatesahugeclassofunforeseeninteractions.

2.FUNCTIONALvs.IMPERATIVEPROGRAMMING
Thefunctionalprogrammingparadigmwasexplicitlycreatedtosupportapurefunctionalapproach toproblemsolving.Functionalprogrammingisaformofdeclarativeprogramming.Incontrast, mostmainstreamlanguages;includingobjectorientedprogramming(OOP)languagessuchasC#, Visual Basic, C++, and Java were designed to primarily support imperative (procedural) programming.

Withanimperativeapproach,adeveloperwritescodethatdescribesinexactingdetailthestepsthat the computer must take to accomplish the goal. This is sometimes referred to as algorithmic programming. In contrast, a functional approach involves composing the problem as a set of functionstobeexecuted.Wedefinecarefullytheinputtoeachfunction,andwhateachfunction returns. The following table describes some of the general differences between these two approaches.

Characteristic

Imperativeapproach Howtoperformtasks (algorithms)andhowto trackchangesinstate. Important. Important.

Functionalapproach

Programmerfocus

Whatinformationisdesiredandwhat transformationsarerequired. Nonexistent. Lowimportance.

Statechanges Orderofexecution

Primaryflowcontrol

Loops,conditionals,and Functioncalls,includingrecursion. function(method)calls.

Primarymanipulation Instancesofstructuresor Functionsasfirstclassobjectsanddata unit classes. collections.

3.FEATURESOFHASKELL
3.1PURE
Haskelliscalledpurebecauseitdoesnotallowsideeffects.Asideeffectissomethingthataffects thestateoftheworld.Forinstance,afunctionthatprintssomethingtothescreenissaidtobe sideeffecting, as is a function which affects the value of a global variable. Of course, a programminglanguagewithoutsideeffectswouldbehorriblyuseless;Haskellusesasystemof monadstoisolateallimpurecomputations fromtherestoftheprogramandperformtheminthesafeway. Purely functional programs operate only on immutable data. This is possible because on each modificationanewversionofadatastructureiscreatedandtheoldoneispreserved.Therefore, datastructuresarepersistentasitispossibletoreferalsotooldversionsofthem.Ifthereareno more references to the old version the unrefered data can be collected by automatic memory management,suchasagarbagecollector.Often,biggerdatastructures share theirpartsbetween versionsanddonotconsumeasmuchmemoryasallversionsseparately. Pure computations yield the same value each time they are invoked. This property is called referential transparency and makes possible to conduct equational reasoning on the code. For instanceify=fxandg=hyythenweshouldbeabletoreplacethedefinitionofgwithg=h(fx) (fx)andgetthesameresult,onlytheefficiencymightchange.

3.2STRONGLYTYPED
Haskellhasthefollowingbuildinbasicdatatypes:

Bool:FalseorTrue Char:thesetofUnicodecharacters Integer:arbitraryprecisionintegernumbers Int:fixedprecisioninteger,atleast[229,2291]

Float:realfloatingpointnumber,singleprecision Double:doubleprecision

Wecanusethefollowingwaystodefinecomplexdatatypesoutofotherdatatypesusingdata constructors:

Enumeration Lists Tuples Recursion Listcomprehension

EnumerationissimilartothecodetypesofPascal,i.e.wedefinedirectlyallelementsofadatatype byexplicitlymentioningthem. Example:dataWeekday=Mo|Tu|We|Th|Fr|Sa|Su Mo,Tu,We,Th,Fr,Sa,SuarethedataelementsofthetypeWeekday.Theyarealsosocalled constructors(theycanbeusedtoconstructthedatatype). Haskelltreatslistssomewherebetweenprimitiveandcomplexdatatypes,sinceitalreadyprovides listconstructorsanddoesnotrequiretoexplicitlydefinelists Ifadenotesadatatype,then[a] denoteslistsoverthisdatatype.[Integer]denoteslistcontainingintegers.[]denotestheemptylist. The:constructorcanalsobeusedtoproducelists. TuplesareverysimilartotherecordconstructinPascal.Tuplescaneitherusethetupleconstructors (,,)(withn1commas,ifwedefineanntuple)or,forparameterizedtupletypes,wecandefine ourownconstructors. dataDate=(Day,Month,Year) dataCartProducta=Prodaa a is here a type variable indicating the parameter of the parameterized type. Haskell allows a programmertodefinecomplexdatatypesusingthedatastatement: dataMybool=MyFalse|MyTrue

3.3STATICALLYTYPED
Haskell'sstatictypesystemdefinestheformalrelationshipbetweentypesandvalues.Thestatic type system ensures that Haskell programs are type safe; that is, that the programmer has not mismatchedtypesinsomeway.Forexample,wecannotgenerallyaddtogethertwocharacters,so theexpression'a'+'b'isilltyped.Themainadvantageofstaticallytypedlanguagesiswellknown: All type errors are detected at compiletime. Not all errors are caught by the type system; an expressionsuchas1/0istypablebutitsevaluationwillresultinanerroratexecutiontime.Still,the typesystemfindsmanyprogramerrorsatcompiletime,aidstheuserinreasoningaboutprograms, andalsopermitsacompilertogeneratemoreefficientcode(forexample,noruntimetypetagsor testsarerequired).

Thetypesystemalsoensuresthatusersuppliedtypesignaturesarecorrect.Infact,Haskell'stype systemispowerfulenoughtoallowustoavoidwritinganytypesignaturesatall;wesaythatthe typesysteminfersthecorrecttypesforus.Nevertheless,judiciousplacementoftypesignaturesisa good idea, since type signatures are a very effective form of documentation and help bring programmingerrorstolight. Haskellautomaticallyinfersthemostgeneraltype.Forexample,thetypeoffoldrisinferredtobe: (a>b>b)>b>[a]> b,whichcanbereadasfollows:foldrtakesasargumentabinaryoperator, whoseinputvaluescanbeofanytypesaandbandwhose outputvalueisoftypeb,andreturnsasitsresultafunctionfwhichtakesavalueoftypebasinput andwhichreturnsasitsresultafunctionfwhichtakesalistofvaluesoftypeaasinput,and whichreturnsasitsresultavalueoftypeb.Theinferredtypeoffoldrshowsthatitcanalsobeused todefinefunctionswheretheinputtypesofitsfirstoperatorargumentaredifferent.

3.4FUNCTIONAL
Inafunctionallanguage,everything(evenaprogram)isafunction.Thus,writingaprogramis actuallywritingafunction.Wecanwritemanyfunctionsinasinglefile;thatis,wecanhavemany programsinasinglefile.Eachfunctionthenmayuseotherfunctionstocalculateitsresult.There aremanypredefinedfunctionsavailablelikeinotherprogramminglanguages.Thesefunctionsare

includedintheHaskellPreludeandintheHaskellLibraries.

Writingafunctionconsistsoftwoparts.First,wehavetodefinethetypesfortheargumentsandthe result.e.g.:

doubleIt::Integer>Integer

ThenameofournewfunctionisdoubleIt.The::separatesthenameofthefunctionfromthetype definition. Theparametertypesareseparatedfromeachother andfromthereturntypeby >. Therefore,thedeclarationabovereadsdoubleItisafunctionwithoneIntegerparameter,returning Integer.

Thesecondpartofwritingafunctionistheconcreteimplementation,e.g.:

doubleItx=2*x

Thedifferentmethodsfordefiningfunctionsare

Patternmatching
fac::Int>Int fac0=1 facn=n*fac(n1)

Conditionalexpression
sign1::Int>String sign1x= ifx<0then"negative" elseifx>0then"positive" else"zero"

Guards
ab::Int>Int abn |(n>=0)=n |otherwise=(n)

Casestatement
cas::Int>Int casx= casexof 0>1 1>5 2>2

"where"clausetoholdlocaldefinitions
sumSq::Int>Int>Int sumSqxy=sqX+sqY where sqX=x*x sqY=y*y

3.5CURRYING
Curryingistheprocessoftransformingafunctionthattakesmultipleargumentsintoafunctionthat takesjustasingleargumentandreturnsanotherfunctionifanyargumentsarestillneeded. f::a>b>c isthecurriedformof g::(a,b)>c

WecanconvertthesetwotypesineitherdirectionswiththePreludefunctionscurryanduncurry. f=curryg g=uncurryf Bothformsareequallyexpressive.Itholds fxy=g(x,y), howeverthecurriedformisusuallymoreconvenientbecauseitallowspartialapplication.

add::Int>Int>Int addxy=x+y addOne=add1

Inthisexample, addOne istheresultofpartiallyapplying add.Itisanewfunctionthattakesan integer,adds1toitandreturnsthatastheresult.Theimportantpropertyhereisthatthe>operator isrightassociative,andfunctionapplicationisleftassociative,meaningthetypesignatureofadd actuallylookslikethis: add::Int>(Int>Int) Thismeansthataddactuallytakesoneargumentandreturnsafunctionthattakesanotherargument andreturnsanInt.InHaskell,allfunctionsareconsideredcurried:Thatis,allfunctionsinHaskell takejustsinglearguments. Thisismostlyhiddeninnotation,andsomaynotbeapparent.Let'stakethefunction div::Int>Int>Int whichperformsintegerdivision.Theexpressiondiv112unsurprisinglyevaluatesto5.Butthere's morethat'sgoingonthanimmediatelymeetstheuntrainedeye.It'satwopartprocess.First, div11 isevaluatedandreturnsafunctionoftype Int>Int

Thenthatresultingfunctionisappliedtothevalue2,andyields5.We'llnoticethatthenotationfor typesreflectsthis:wecanread Int>Int>Int incorrectlyas"takestwo Intsandreturnsan Int",butwhatit's really sayingis"takesan Int and returnssomethingofthetypeInt>Int"thatis,itreturnsafunctionthattakesanIntandreturns an Int.(Onecanwritethetypeas Int x Int > Int ifwereallymeantheformerbutsinceall functionsinHaskellarecurried,that'snotlegalHaskell.

Alternatively,usingtuples,wecanwrite(Int,Int)>Int,butkeepinmindthatthetupleconstructor (,) itself can be curried.Much of the time, currying can be ignored. The major advantage of consideringallfunctionsascurriedistheoretical:formalproofsareeasierwhenallfunctionsare treateduniformly(oneargumentin,oneresultout).

3.6LISTCOMPREHENSIONS
Listcomprehensionisasyntacticconstructavailableinsomeprogramminglanguagesforcreatinga list based on existing lists. It follows the form of the mathematical setbuilder notation (set comprehension.)asdistinctfromtheuseofmapandfilterfunctions.Considerthefollowingexample insetbuildernotation.

Thiscanberead,"Sisthesetofall2*xwherexisaniteminthesetofnaturalnumbers,forwhich xsquaredisgreaterthan3."

Intheexample:

xisthevariablerepresentingmembersofaninputset. Theinputsetis . x2>3isapredicatefunctionactingasafilteronmembersoftheinputset. And isanoutputfunctionproducingmembersofthenewsetfrommembersofthe inputsetthatsatisfythepredicatefunction.

Thebracketscontaintheexpressionandtheverticalbarandcommaareseparators.

Alistcomprehensionhasthesamesyntacticcomponentstorepresentgenerationofalistinorder fromaninputlistoriterator:

Avariablerepresentingmembersofaninputlist. Aninputlist(oriterator). Anoptionalpredicateexpression. Andanoutputexpressionproducingmembersoftheoutputlistfrommembersoftheinput iterablethatsatisfythepredicate.

Listsaretodeclarativelanguageswhatarraysaretoimperativelanguages.Becuaselistsareso widelyused,aspecialnotationhasbeenintroducedinHaskellforconstructinglists.Thisnotationis calledlistcomprehension(inanalogywithsetcomprehensioninsettheory).InHaskell'slist comprehensionsyntax,thissetbuilderconstructwouldbewrittensimilarly,as: s=[2*x|x<[0..],x^2>3] Here,thelist[0..]represents ,x^2>3representsthepredicate,and2*xrepresentstheoutput expression.

Supposexsisthelist[1,2,3,4,5,6],thenthesetcomprehension [2*x|x<xs] denotesthelist[2,4,6,8,10,12],obtainedbymultiplyingeachlistinxsby2.Inalistcomprehension[ E|P<LExp],werefertoEasthebodyandP<lExpastheselector;notethatLExpcanbeany expressionofalisttype,Pcanbeapattern,andEanyexpressioncontainingthevariablesinP.The orderofgenerationofmembersoftheoutputlistisbasedontheorderofitemsintheinput.

List comprehensions give results in a defined order, (unlike the members of sets); and list comprehensionsmaygeneratethemembersofalistinorder,ratherthanproducetheentiretyofthe listthusallowing,forexample,thepreviousHaskelldefinitionofthemembersofaninfinitelist.

3.7LAZYEVALUATION
Lazyevaluation(ordelayedevaluation)isthetechniqueofdelayingacomputationuntilsuchtime astheresultofthecomputationisknowntobeneeded.

The actions of lazy evaluation include: performance increases due to avoiding unnecessary calculations,avoidingerrorconditionsintheevaluationofcompoundexpressions,theabilityto constructinfinite datastructures,andtheabilitytodefine controlstructures asregularfunctions ratherthanbuiltinprimitives.

Languages that use lazy actions can be further subdivided into those that use a callbyname evaluationstrategyandthosethatusecallbyneed.Mostrealisticlazylanguages,suchasHaskell, usecallbyneedforperformancereasons,buttheoreticalpresentationsoflazyevaluationoftenuse callbynameforsimplicity.

Theoppositeoflazyactionsiseagerevaluation,alsoknownasstrictevaluation.Eagerevaluationis theevaluationbehaviorusedinmostprogramminglanguages. Haskellevaluatesexpressionsusinglazyevaluation: 1. Noexpressionisevaluateduntilitsvalueisneeded. 2. Nosharedexpressionisevaluatedmorethanonce;iftheexpressioniseverevaluatedthen theresultissharedbetweenallthoseplacesinwhichitisused. Lazyfunctionsarealsocallednonstrictandevaluatetheirargumentslazilyorbyneed.

3.8RECURSION
Inimperativelanguagestoperformrepeatedoperationswemakeuseofloops.Thisisn'tdirectly possibleinHaskell,sincechangingthevalueofthewouldnotbeallowed.However,wecanalways translatealoopintoanequivalentrecursiveform.Theideaistomakeeachloopvariableinneedof updatingintoaparameterofarecursivefunction.Butrecursionisexpensiveintermsofbothtime andspace.

Whenafunctioniscalled,thecomputermust"remember"theplaceitwascalledfrom,thereturn address,sothatitcanreturntothatlocationwiththeresultoncethecalliscomplete.Typically,this informationissavedonthestack,asimplelistofreturnlocationsinorderofthetimesthatthecall locations they describe were reached. Sometimes, the last thing that a function does after completingallotheroperationsistosimplycallafunction,possiblyitself,andreturnitsresult.But inthiscase,thereisnoneedtoremembertheplacewearecallingfrominstead,wecanleavethe stack alone, and the newly called function will return its result directly to the original caller. Convertingacalltoabranchorjumpinsuchacaseiscalledatailcalloptimization.Notethatthe tailcalldoesn'thavetoappearlexicallyafterallotherstatementsinthesourcecode;itisonly importantthatitsresultbeimmediatelyreturned,sincethecallingfunctionwillnevergetachance todoanythingafterthecalliftheoptimizationisperformed.

Tailrecursion(ortailendrecursion)isaspecialcaseofrecursioninwhichthelastoperationof the functionis a recursivecall.Suchrecursionscan be easily transformedtoiterations. Replacingrecursionwithiteration,manuallyorautomatically,candrasticallydecreasetheamount of stack spaceusedandimproveefficiency.Thistechniqueiscommonlyusedwith functional programming languages,wherethedeclarativeapproach andexplicithandlingof state promote theuseofrecursivefunctionsthatwouldotherwiserapidlyfillthecallstack.

3.9HIGHERORDERFUNCTIONS
Ahigherorderfunctionisafunctionthattakesotherfunctionsasargumentsorreturnsafunctionas result.Thethreemostusefulhigherorderfunctionsaremap,foldandfilter.

map:Ittakesintwoinputsafunction,andalist.Itthenappliesthisfunctiontoeveryelementin
thelist.

map::(a>b)>[a]>[b]

mapfxs=[fx|x<xs] Main>map(+1)[1..5] [2,3,4,5,6]

fold:foldtakesinafunctionandfoldsitinbetweentheelementsofalist.
fofoldl::(a>b>a)>a>[b]>a foldlfz[]=z foldlfz(x:xs)=foldlf(fzx)xs Thecommandtoaddthefirst5numberswithfold. foldl(+)0[1..5] Foldtaketheelementsofthelistandwritethemoutseparatelywithaspacebetweeneach. 1 2 3 4 5

Andnowwe fold thefunctionintotheelements.Todothis,wewritethefunctionintheempty spacesbetweentheelements.

Notethatthere'snothingbeforethefirst(+).That'sbecausewecanspecifyastartingpoint.Sothat's thesecondinputfoldlasksforastartingpoint.Inthiscase,wesaidzero,sowe'llputitinthere. 0 + 1 + 2 + 3 + 4 + 5

Andallthisgivesusthefinalresult Main>foldl(+)0[1..5] 15 Andifwechangethestartingpoint,wegetthecorrespondinganswer. Main>foldl(+)1[1..5] 16 Main>foldl(+)10[1..5] 25 Wecanalsogothroughthelistfromrighttoleft,ratherthanlefttoright.That'swhyweusefoldl andfoldr.Therearecaseswherefoldingfromtheleftgivesusdifferentresultstofoldingfromthe right.Italldependsonwhatfunctionwe'refolding.Forexample, Main>foldr(div)7[34,56,12,4,23] 8 Main>foldl(div)7[34,56,12,4,23] 0

filter:Ittakesina'test'andalist,anditchucksoutanyelementsofthelistwhichdon'tsatisfy
thattest. filter::(a>Bool)>[a]>[a] filterpxs=[x|x<xs,px] Main>filter(even)[1..10] [2,4,6,8,10] Main>filter(>5)[1..10] [6,7,8,9,10]

3.10POLYMORPHISM
Polymorphismisa programminglanguage featurethatallowsvaluesofdifferent datatypes tobe handledusingauniforminterface.Theconceptofparametricpolymorphismappliestobothdata

typesand functions.Afunctionthatcanevaluatetoorbeappliedtovaluesofdifferenttypesis knownasapolymorphicfunction.Adatatypethatcanappeartobeofageneralizedtype(e.g.,alist withelementsofarbitrarytype)isdesignatedpolymorphicdatatypelikethegeneralizedtypefrom whichsuchspecializationsaremade. Therearetwofundamentallydifferentkindsofpolymorphism.Iftherangeofactualtypesthatcan beusedisfiniteandthecombinationsmustbespecifiedindividuallypriortouse,itiscalledAdhoc polymorphism.Ifallcodeiswrittenwithoutmentionofanyspecifictypeandthuscanbeused transparentlywithanynumberofnewtypes,itiscalledparametricpolymorphism. Haskellisastronglytypedlanguage,whichmeansthateveryexpressionhasatype,andthatthe interpretercaninferthetypeofanexpressionfromthetypesofitssubexpressions.Allthelist operators,functionsandexpressionshavetypes.Let'slookatthelengthfunction.Clearly,length returnsanumberofsomekind;infact,itreturnsa32bitinteger,i.e.,anInt.Andclearlyittakesa listasargument,butwhatkindoflist?Theansweristhatittakesanykindoflistasargument: length::[a]>Int Thetypeoflength'sargumentis[a],whichmeansalistwhoseelementsareofanytypea.Thisais simplyanamestandingforanyHaskelltype;whenweevaluatelength"word",forexample,thea standsfor(ormoreprecisely,isinstantiatedto)Char,andwhenweevaluatelength[(1,2)],thea standsfor(isinstantiatedto)(Int,Int).Thisisanexampleofparametricpolymorphism, In Haskell, type classes provide a structured way to control ad hoc polymorphism, or overloading.Let'sstartwithasimple,butimportant,example:equality.Therearemany typesforwhichwewouldlikeequalitydefined,butsomeforwhichwewouldnot.Forexample, comparingtheequalityoffunctionsisgenerallyconsideredcomputationallyintractable,whereaswe oftenwanttocomparetwolistsforequality.Tohighlighttheissue,considerthisdefinitionofthe function elem which tests for membership in a list:

x`elem`[]=False x`elem`(y:ys)=x==y||(x`elem`ys) Intuitivelyspeaking,thetypeofelem"ought"tobe:a>[a]>Bool.Butthiswouldimplythat==has

type a>a>Bool, even though we just said that we don't expect == to be defined for all types.Furthermore,evenif==weredefinedonalltypes,comparingtwolistsforequalityisvery differentfromcomparingtwointegers.Inthissense,weexpect==tobeoverloadedtocarryon thesevarioustasks. Typeclassesconvenientlysolvebothoftheseproblems.Theyallowustodeclarewhichtypesare instancesofwhichclass,andtoprovidedefinitionsoftheoverloadedoperationsassociatedwitha class.

DefiningclassesinHaskell
classEqawhere (==),(/=)::a>a>Bool

CreatingInstanceofClassEq
instanceEqIntegerwhere x==y=x`integerEq`y instanceEqFloatwhere x==y=x`floatEq`y

ClassExtension
classEqa)=>Ordawhere (<),(<=),(>=),(>)::a>a>Bool max,min::a>a>a

TypeClassesinHaskell

4.APPLICATIONAREAS
4.1NATURALLANGUAGEINTERFACES Parsercombinators
LFPhasbeenusedinaconventionalwaytoimplementarangeofparsersthathavealreadybeen implemented in other programming languages. parser combinators is an approach to parser constructionwhichisuniquetofunctionalprogramming.Theuseofparsercombinatorswasfirst proposed by Burgein1975, Theideaistoconstructmorecomplexlanguageprocessors from simplerprocessorsbycombiningthemusinghigherorderfunctions(theparsercombinators).This approach was developed further by Wadler [1985] who suggested that recognizers and parsers shouldreturnalistofresults.Multipleentriesinthelistarereturnedforambiguousinput,andan empty list of successes denotes failure to recognize the input. Fairburn promoted combinator parsing by using it as an example of a programming style in which form follows function: a languageprocessorthatisconstructedusingparsercombinatorshasastructurewhichisverysimilar tothegrammardefiningthelanguagetobeprocessed.

ConstructionofMorphologies

A morphology is a system which explains the internal structure of words.Regular nouns have relativelysimplemorphologicalstructure.Forexample,cat,cat++s,andcat++++s, whereasirregularnounsandverbshavemorecomplexmorphology.Themorphologyofaparticular language can be defined using a set of inflection tables. The conventional approach to morphologicalrecognitionistocompilethetablesintofinitestateautomata,andthentoparse wordsasregularexpressions.Asanalternative,Pembeci[1995]hasbuiltamorphologicalanalyzer forTurkishusingparsercombinators implementedinMirandaandclaimsthattheanalyzercanparseapproximately99%ofallword formsinTurkish.Pembecialsoclaimsthatallmorphologicalprocesseshavebeen

implemented,andthatanumberofadvantagesresultfromuseofparsercombinators,including clarity and modifiability of the code. Forsberg [2004], and Forsberg and Ranta [2004] have developedanalternativeapproach,calledFunctionalMorphologywhichisimplementedinHaskell. ItisbasedonHuetstoolkit,Zen,[Huet2003,2004]whichHuetusedtobuildamorphologyfor Sanskrit. In this approach, inflection parameters are defined using algebraic data types,and paradigmtablesareimplementedasfinitefunctionsdefinedoverthesetypes.

Semanticanalysis

ComputationallytractableversionsofMontaguelikesemantictheoriescanbeimplementedinLFP bythedirectencodingofthehigherorderfunctionalsemantics.

4.2PARALLELPROGRAMMING NestedDataParallelism

NestedDPisgreatfor programmersduetoitsmodularity. It opensupamuchwiderrangeof applications:


Sparsearrays,variablegridadaptivemethods(e.g.BarnesHut) Divideandconqueralgorithms(e.g.sort) Graphalgorithms(e.g.shortestpath,spanningtrees) Physicsenginesforgames,computationalgraphics(e.g.Delaunytriangulation)

Machinelearning,optimisation,constraintsolving.

5.HASKELLINPRACTICE
LOLITA:LOLITAisanaturallanguageprocessing(NLP)systemprovidingbothcoreNLP capabilitiesandanumberofprototypeapplications.Thecoreofthesystemisbasedonthreemain capabilities:

1. conversion of English language text to an internal (semantic network based) representationofthetext'smeaning 2. inferencesinthesemanticnetwork 3. conversionofportionsofthesemanticnetworktoEnglish

Linkchk : Linkchkisanetworkinterfacelinkpingmonitor.ItsupportsbothIPv4andIPv6.It
worksbymonitoringtheroutingtableandpingingthegateway(nexthop)ofanetworkinterface. Whenthelinkisupandfunctioningthepingtimeisdisplayedinasmallgtkwindow,otherwisethe linkstatusisdisplayed.linkchkcanalsoruninatty.

HWSWP:TheHaskellWebServerWithPlugins(HWSWP)isa.simpleHTTPserverwritten
inHaskell,originallyimplementedbySimonMarlowandupdatedbyMartinSjogren.

Hoogle : HoogleisaHaskellAPIsearchengine.Itallowsustosearchbyeithername,orby
approximate type signature. The standard web interface to Hoogle is available at http://www.haskell.org/hoogle/.

House:HaskellUser'sOperatingSystemandEnvironment.Houseisademoofsoftwarewritten
in Haskell,runninginastandaloneenvironment.Itisasystemthancanserveasaplatformfor exploring various ideas relating to lowlevel and systemlevel programming in a highlevel functionallanguage.

6.CONCLUSION
Haskell 98 is complete and is the current official definition of Haskell. We expect that this languagewillbesupportedinthelongtermevenasnewextensionsareaddedtoHaskell;compilers willcontinuetosupportHaskell98(viaaspecialflag). Thelanguageevolvesandnumerousextensionshavebeenproposedandmanyofthemhavebeen implementedinsomeHaskellsystems;forexamplepatternguards,scopedtypevariables,multi parametertypeclasses,localuniversalandexistentialquantification.TheHaskellmailinglistsarea forumfordiscussingnewlanguagefeatures.Haskell'isthenextofficialversion.

Das könnte Ihnen auch gefallen