[SOLVED] Microsoft PowerPoint Week2.pptx

$25

File Name: Microsoft_PowerPoint__Week2.pptx.zip
File Size: 301.44 KB

5/5 - (1 vote)

Microsoft PowerPoint Week2.pptx

20220914

Copyright By Assignmentchef assignmentchef

Ch1:StartingOut
Ch2:BelievetheType

UniversityoftheFraserValley

COMP481:FunctionalandLogicProgramming

Terminology

referentialtransparencyguaranteesafunctionreturnsthe
sameresultwhencalledwiththesameparametervalues

lazyHaskellwillnotcalculatevaluesuntilnecessary
(allowsyoutomakeseeminglyinfinitedatastructures)

staticallytypedallthingsaredeterminedatcompiletime

typeinferencecanletHaskelldeterminewhattypesomething
belongsto,butcanstillstatethetypeofsomethingifyouwant

20220914

MathOperations

Typicaladdition,subtraction,multiplication,division
floatingpointdivision/
integerdivision,e.g.:
div 10 4 evaluatesto2 andnot2.5

12 mod 7

True && False
True || False
not True

Comparison
hello == hello

20220914

Takeamomenttoreadtheerrormessagewhenattemptingtosum
twovaluesofdifferenttypes,e.g.:5 + llama.

theoperationswrittenbetweentwovalues(suchas*):

areconsideredfunctionswithtwoparameters

aredescribedasinlinewhenwritteninbetweenitsarguments

canbewritteninprefixstyle,i.e.:(*) 2 3 evaluatesto6

Afewdifferentkindsoffunctions:

20220914

Listfunctions:

replicate

20220914

ListCreation
withRanges

[2,4..20]

[20,19..1]

take 24 [13,26..]

take 10 (cycle [1,2,3])

take 12 (cycle LOL )

take 10 (repeat 5)

replicate 3 10

watchoutwithusingrangesandfloatingpointaccuracy

[0.1, 0.3 .. 1]

Comprehensions

[2*x | x <- [1..10]] youcanaddpredicatesafteracomma,andhaveasmanypredicatesasyouwanttofilteryourlist [2*x | x <- [1..10], odd x] youcanhavemultiplevariables,eachassignedwithalist,sotheresultislikeacrossproduct [x*y | x <- [3, 5], y <- [2, 4, 6]] caninvolvemorecomplexexpressions boombangs xs =[if x < 10 then BOOM! else BANG! | x <- xs, odd x]20220914ListAccess use`!!` toaccessoneelementusinganindex [1, 2, 3] !! 0 again,stringsarealsolistsofcharacters: hello !! 4Wecanalsohavelistsinsideoflists: [ [1,2,3], [4,5,6], [7,8,9] ] Tuples20220914TupleTypes differentnumbersofelementsaretreatedasdistincttypes so,a2tupleisconsidereddifferenttypefroma3tuple fortupleswithdifferenttypesincorrespondingelementsarealtogetherdifferenttypesaswell e.g.:(1, ‘a) differenttypefrom(‘a’, 1) cancompareelementsofthesametype cannotcomparetuplesofdifferentlengths fst returnsthefirstelementinapair snd returnsthesecondelementinapair theaboveonlyworkon2tuples zip functiontakestwoinputlistsandcreatesalistoftupleswithcorrespondingvaluesfromtheinputlists zip [1..] [“apple”, “orange”, “cherry”, “mango”]20220914 Chapter2Itisjusteasiertousemultilinestatementsinghci thantowritescriptsinfilesforexamplesthatareonlyafewlinesatatime use:{:} formultiline use:set +m formultilinewithoutbracesDifferentmultilinehasdifferentwaystoexit: foramistakewith:{ justclosewith:} andstartover fora let multiline,toexitjustpressENTER twiceWithoutmultilinebraces,codemustfollowlayoutsyntax: mostly,justindentthenextlinetothesamecolumnasthevariablenameonitspreviousline thisisonlyforsomeexpressionsthatcanspanmultiplelines20220914TupleTypesEverythinginHaskellhasatypedeterminedatcompile youdonotneedtoexplicitlydeclaretypesifthereisenoughotherinformationforHaskell :: readsas”hastypeof” e.g.:(True, ‘a’) :: (Bool, Char) :t letsuscheckthetypeofwhateverfollowsthecommand `Int`boundedbyminandmaxvalues dependingonyourarchitecture,fora64bitCPU,likelytheboundsare263 and263 `Integer`unbounded,butlessefficientthan`Int` `Float`realnumberstosinglefloatingpointprecision `Double`realnumberstodoublefloatingpointprecision `Bool`onlythetwoexpectedvalues`True`or`False` `Char`asingleUnicodecharacter `[Char]` isthesametypeasthe`String` type wesawtuplestheirtypesalsodependontheirlength notethatanemptytupleisalsoatype`()` tuplescanhaveatmost62elements,buttheoreticallythereareaninfinitenumberoftypes20220914Thetypeofafunctioncouldinvolvelists,butliststhemselvescouldcontainsomearbitrarytype: so,thedeclarationwillinvolveaplaceholderfortheelementtype,suchas`a` e.g.: :t head;head :: [a] -> a

e.g.: :t fst; fst :: (a, b) -> a

Notethatthetypeof`fst`functiondescribesthefirst
elementinthepair`a`tohavethesametypeasthe
returnvalueofthe`fst`function.

TypeClasses

Fornow,thinkofatypeclassasmostlythesameconceptasan
abstractinterfaceinobjectorientedprogramming

typeclassdeclares,butnotanimplementationforitsfunctions

anyclassbelongingtothetypeclass
willneedtoimplementfunctionbehaviour

equalityisagoodexampleofafunction
thatmakesuseoftypeclassesinitspattern

try`:t (==)`

everythingbeforethe`=>`iscalledaclassconstraint

anyofthevaluesinplaceof`a`mustbeofthe`Eq`typeclass

forourfirstexampleofatypeclassis`Eq`,
ofwhicheverythinginHaskellisaninstance
(exceptforinput/outputtypes)

20220914

Eq & Classes

The`Eq`typeclasssupportsequalitytesting.

soifafunctionhasan`Eq`classconstraintforoneofitstype
variables,thenthatfunctionmustimplementBOTH
`==`and`/=`withinitsdefinition

definitionmeansthefunctionsstatementsofexecution

The`Ord`typeclassisusedbytypesthatneedarrange
theirvaluesinsomeorder

try`:t (>)`

the`compare`functiontakestwoinputvaluesbothwithtype
aninstanceof`Ord`

thereturntypeis`Ordering`

`Ordering`isatypewithvalues`GT`,`LT`,`EQ`

Alltypeswehaveseensofarexceptfunctionsare
instancesofthe`Show`typeclass

the`show`functionwillprintitsinputasastring

The`Ord`typeclassisusedbytypesthat
needtoarrangetheirvaluesinsomeorder

try`:t (>)`

20220914

TypeClass

Alltypeswehaveseensofarexceptfunctionsareinstancesofthe
Read typeclassaswell.

theread function(inverseoftheshow function)

read takesaStringtypevalueasinputandreturnswhatvalue
wouldbeexpectedwhenusedincontext

Forexample:`read True || False`

theabovecontextwouldexpectavalueoftype`Bool`inplaceof
the`read True`expression

`read 4` willresultinanerror,becausetheexpressionisnot
usedinanycontext,soitdoesnotknowwhattypetoexpect

Annotations

Nowwewillneedtypeannotations sometimeswhenwewantto
specifytheresultingtypeofanexpression.

append`::`withacorrespondingtypetotheexpression

e.g.:`read 5 :: Int`

e.g.:`(read 5 :: Float) * 4`

wemayavoidanannotationwhenHaskellcaninferthetype

e.g.:`[read True, False, True]`

20220914

The`Enum`typeclassdescribesanytypethathasvalues
whicharetotallyordered:

theadvantageistobeabletospecifylistrangeswith`..`

its`pred`functionwillreturnthevaluethatdirectlyprecedesits
inputvalueinthetotalorder

its`succ`functionwillreturnthenextvaluedirectlyafterit
inputvalueinthetotalorder

Examplesoftypesinthistypeclass:

(), Bool, Char, Ordering,
Int, Integer, Float, Double

trytheaboveincreatingafewlists

TypeClass

Itismorehelpfultolookatanexamplefunctionthat
usesthe`Bounded`typeclass:

the`maxBound`functionhasaninterestingtype

:t maxBound;maxBound :: Bounded a => a

thetextbookdescribesthiskindoffunctionaspolymorphicconstants

i.e.:`maxBound`hasnoinputparameters,butspecifiesthereturntype

tupleswithallelementtypesasinstancesof`Bounded`are
altogetherconsideredaninstanceof`Bounded`aswell

20220914

TypeClass

Lookat`:t 20`

similartypeas`maxBound`,butwithtypeclass`Num`instead

soavaluesuchas`20`isalsoapolymorphicconstant
canactlikeanytypethatsaninstanceofthe`Num`typeclass
`Int, Integer, Float, Double`

Try`t: 20 :: Double`

considerthemultiplicationoperator`:t (*)`
acceptstwonumbersandreturnsanumberofthesametype
e.g.:`(5 :: Int) * (6 :: Integer)`willcauseatypeerror
e.g.:`5 * (6 :: Integer)` hasnosucherror
`5` canactlikeeitheran`Int`oran`Integer`,
butnotbothatonce

tobeaninstanceof`Num`,atypemustalsobe
aninstanceof`Show`and`Eq`

TypeClass

envelopesthe`Float`and`Double`types

examplesoffunctionstotrythetype`:t`are

`cos`,and

20220914

TypeClass

envelopesthe`Int`and`Integer`types

onlywholenumbers

Anexamplewithmorethanoneclassconstraint:

:t fromIntegral
fromIntegral :: (Integral a, Num b) => a -> b

returnsamoregeneraltypeforthesamevalue

youcanuse`fromIntegral`tosmoothlycombineexpressions
thatusemixednumerictypes

e.g.:`fromIntegral (length [1,2,3,4]) + 3.2`

Converting
FloatValues

ToconvertaFloatinginstancevaluetoanIntegralone:

floor 3.2

ceiling 3.2

Justconsiderhowthesefunctionsworkwithnegativenumbers:

floor (-3.2)

ceiling (-3.2)

Trywithalternativenotationtoparentheses:

floor $ -3.2

ceiling $ -3.2

20220914

FinishingUp

becausetypeclassesareessentiallyabstractinterfaces,atype
canbeaninstanceofmanydifferenttypeclasses

sometimesatypemustbeaninstanceofonetypeclassinorder
tobeaninstanceofanothertypeclass

e.g.:aninstanceof`Ord`mustfirstbeaninstanceof`Eq`

thismakessensefromourexperienceinmath

comparingtwothingsforordering

weshouldalsobeabletocheckwhethertwoofthosethingsareequal

wecallthisimplicationbetweentypeclassesaprerequisite

20220914

ThankYou!
Questions?

CS: assignmentchef QQ: 1823890830 Email: [email protected]

Reviews

There are no reviews yet.

Only logged in customers who have purchased this product may leave a review.

Shopping Cart
[SOLVED] Microsoft PowerPoint Week2.pptx
$25