Table Of ContentWhat Sequential Games, the Tychonoff Theorem
and the Double-Negation Shift have in Common
Mart´ınEscardo´ PauloOliva
UniversityofBirmingham,UK QueenMaryUniversityofLondon,UK
[email protected] [email protected]
Abstract selection functions (x -> r) -> x for a type x, and the output
isasingle,combinedselectionfunction([x] -> r) -> [x]for
Thisisatutorialformathematicallyinclinedfunctionalprogram-
thetype[x]oflistsofelementsofthetypex.Iftheinputlistof
mers, based on previously published, peered reviewed theoretical
selectionfunctionsis
work.Wediscussahigher-typefunctional,writtenhereinthefunc-
tional programming language Haskell, which (1) optimally plays ε=[ε ,ε ,...,ε ,...],
0 1 n
sequential games, (2) implements a computational version of the
Tychonoff Theorem from topology, and (3) realizes the Double- thenthemathematicalnotationfortheoutputofthealgorithmis
NegationShiftfromlogicandprooftheory.Thefunctionalmakes O
ε .
sense for finite and infinite (lazy) lists, and in the binary case it i
amounts to an operation that is available in any (strong) monad. i
Infact,oncewedefinethismonadinHaskell,itturnsoutthatthis Asweshallsee,thedefinitionofthealgorithmamountsto,andcan
amazinglyversatilefunctionalisalreadyavailableinHaskell,inthe infactbeliterallywrittenasarecursivedefinition,
standardprelude,calledsequence,whichiteratesthisbinaryop- O O
ε =ε ⊗ ε ,
eration.ThereforeHaskellprovesthatthisfunctionalisevenmore i 0 i+1
versatilethananticipated,asthefunctionsequencewasintroduced i i
forotherpurposesbythelanguagedesigners,inparticulartheitera- forasuitablebinaryoperation⊗thatcombinestwoselectionfunc-
tionofalistofmonadiceffects(buteffectsarenotwhatwediscuss tions.
here). This algorithm makes sense for both finite and infinite (lazy)
lists,andweshallwriteitinseveraldifferentbutequivalentways.
Categories and Subject Descriptors D.1.1 [Programming tech-
Itisdifficulttogiveageneralspecificationofwhatitdoes,because
niques]:functionalprogramming
itturnsoutthatitperformsavarietyofseeminglyunrelatedtasks:
GeneralTerms Algorithms,languages,theory.
1. Itoptimallyplayssequentialgames.
Keywords Functional programming, Haskell, monad, search, 2. ItimplementsacomputationalmanifestationoftheTychonoff
game theory, optimal strategy, exhaustible set, axiom of choice, Theoremfromtopology.
infinitedata,dependenttype,Agda,topology,logic,foundations.
3. It realizes the Double-Negation Shift (DNS) from logic and
prooftheory(whoseroleistocomputationallyextractwitnesses
1. Anamazinglyversatilefunctional
fromclassicalproofsthatusetheaxiomofcountablechoice).
Perhapsthemostconciseandself-containeddefinitionofthefunc-
Andmore,asdiscussedin[6–8,10–12].Forexample,theso-called
tionalwetodiscussinthistutorialisthis,usingHaskellnotation:
Bekic’s Lemma for fixed-points that arises in domain theory and
bigotimes :: [(x -> r) -> x] -> ([x] -> r) -> [x] programminglanguagesemanticsisaparticularcaseoftheproduct
bigotimes [] p = [] ofselectionfunctions[8].
bigotimes (e : es) p = x0 : bigotimes es (p.(x0:)) Originally, the algorithm was designed to achieve (2), but, by
where x0 = e(\x -> p(x : bigotimes es (p.(x:)))) studyingitinmoredetail,wediscoveredthatitalsoachieves(3)
and(1),inchronologicalorder.Weregardthisasarathersurprising
This is an example of an algorithm that is patently not self-
courseofevents,giventhattheTychonoffTheoremhasn’tappeared
explanatory.Hereisapreliminaryindicationofwhatisgoingon,
sofarinthetheoreticalstudyof(1)and(2),atleastnotexplicitly.
tobeelaborated below.Thinkofrasatype ofgeneralizedtruth
Inanycase,itiscertainlysurprisingthatthesamemathematicalop-
values.Aparticularcaseofinterestwillber = Bool,butnotthe
erationoralgorithmshouldsimultaneouslysolvetheseseemingly
onlyrelevantone.Theinputofthealgorithmisalistofso-called
unrelatedtasks,eachofwhichisfundamentalinitsownright.
Itisthepurposeofthistutorialtoexplainthemainideasbehind
N
the mathematical operation , defined and studied in [6–8, 10–
12].Thisexpositorypaperisaninvitationforthereadertoexplore
Permissiontomakedigitalorhardcopiesofallorpartofthisworkforpersonalor thesereferences,whichgivefullmathematicaldetailsandproofs,
classroomuseisgrantedwithoutfeeprovidedthatcopiesarenotmadeordistributed aswellasmoretechniques,ideasanddirections.
forprofitorcommercialadvantageandthatcopiesbearthisnoticeandthefullcitation
We also implement a number of sample applications in func-
onthefirstpage.Tocopyotherwise,torepublish,topostonserversortoredistribute
tolists,requirespriorspecificpermissionand/orafee. tional programming, such as playing Tic-Tac-Toe (aka Noughts-
MSFP’10, September26,2010,Baltimore,Maryland,USA. and-Crosses),solvingthen-Queenspuzzle,anddecidingequality
Copyright(cid:13)c 2010ACM978-1-4503-0251-7/10/09...$10.00 offunctions(!)oncertaininfinitetypes,amongothers.
Organization. 2. Selection functions. 3. Products of selection find [x] p = x
functions.4.Playinggames.5.TheTychonoffTheorem.6.Mon- find (x:xs) p = if p x then x else find xs p
ads.7.TheDouble-NegationShift.8.Concludingremarks.
forsome, forevery :: [x] -> K Bool x
2. Selectionfunctions forsome = overline.find
forevery xs p = not(forsome xs (not.p))
Ifwedefine
Or,expandingthedefinitions,
type J r x = (x -> r) -> x
forsome xs p = p(find xs p)
then the type specification of the function bigotimes can be
rewrittenas OurdefinitionoftheexistentialquantifieristhesameasinHilbert’s
ε-calculus:
bigotimes :: [J r x] -> J r [x]
∃x p(x) ⇐⇒ p(ε(p)).
TounderstandthetypeconstructorJ,wealsoconsider
Notice that the definition of forevery uses the De Morgan Law
type K r x = (x -> r) -> r forquantifiers,
The type constructor K r is known as the continuation monad, ∀x p(x) ⇐⇒ ¬∃x ¬p(x).
andisrelatedtocontroloperatorssuchascall/cc.Butweshall
Asdiscussedabove,weareinterestedinfinitenon-emptylistsonly,
insteadregarditasatypeofgeneralizedquantifiersoverthetypex,
tomakesuretheproducedselectionfunctionistotal.Forinstance,
withtypeofgeneralizedtruthvaluesr.Asweshallseelater,J r
isamonadtoo,calledtheselectionmonad,andthereisamonad find [1..100] (\x -> odd x && x > 17) = 19
morphism to K r. We shall have occasion to use the morphism forsome [1..100] (\x -> odd x && x > 17) = True
beforewegiveJ rthestructureofamonad:
find [1..100] (\x -> odd x && even x) = 100
overline :: J r x -> K r x
forsome [1..100] (\x -> odd x && even x) = False
overline e = \p -> p(e p)
AselectionfunctionεforasetShastosatisfy:
TheHaskellnotation
1. ε(p) ∈ S,whetherornotthereactuallyissomex ∈ S such
overlinee
thatp(x)holds.
correspondstothemathematicalnotation
2. Ifp(x)holdsforsomex∈S,thenitholdsforx=ε(p).
ε.
Notice that the first condition forces the set S to be non-empty.
We refer to the elements of J r x as selection functions. What Hereisanotherexamplethatweshallneedlater:
overlinedoes,then,istotransformselectionfunctionsintoquan-
findBool :: J Bool Bool
tifiers.Inthiscontext,werefertotheelementsofthefunctiontype
findBool p = p True
(x -> r)aspredicates.
Thisisequivalentto
Terminology Mathematics Haskell Type
findBool p = if p True then True else False
predicate p,q p,q x -> r
selectionfunction ε,δ e,d J r x butitissillytocheckthetwopossiblecases.Thisissobothconcep-
quantifier φ,γ phi,gamma K r x tuallyandforthesakeofefficiency.Infact,thegivendefinitionof
findBooldoesn’tforcetheevaluationoftheexpressionp True,
Withr = Bool,aparticularelementofthetypeK r xistheex-
butthealternativeformulationdoes(hencethegivenformulationis
istential quantifier, or the existential quantification functional to
lazier,inthetechnicalsenseoftheword).
be more precise, which arises when we consider selection func-
tionsforsets.Afterconsideringthisparticularcaseofaselection
2.2 Selectionfunctionsforquantifiers
function,weconsiderthemoregeneralcaseofselectionfunctions
forarbitraryquantifiers,whichincludetheuniversalquantifier,of Ouruseofselectionfunctionsgoesbeyondtheaboveidea.Ifφ(p)
course,butothergeneralizedquantifiersaswell. standsfor∃x∈S p(x),thenHilbert’sconditioncanbewrittenas
In this discussion we adopt the traditional terminology from anequation,
logic that refers to higher-type functions as functionals, and we φ(p)=p(ε(p)),
stress that in logic one usually adopts the terminology higher-
orequivalently,usingthemonadmorphism,astheequation
ordertologicsthatquantifyoverpropositions,andtheterminology
higher-type to formal systems that allow nested function types φ=ε.
(suchasGo¨del’ssystemT andgeneralizations,includingPCFand
Ifthisequationholds,wesaythatεisaselectionfunctionforthe
Haskell).
quantifierφ.Thus,aselectionfunctionforasetSisthesamething
asaselectionfunctionfortheexistentialquantifierofS.
2.1 Selectionfunctionsforsets
Whenφ(p)istheuniversalquantifier∀x∈S p(x)ofthesetS,
A selection function for a set S finds an element of S for which theaboveequivalentequationsamountto
a given predicate holds. But we emphasize that we require our
1. ε(p)∈S.
selection functions to be total. Hence if there is no element of S
satisfyingthepredicate,weselectanarbitraryelementofS,andso 2. Ifp(x)holdsforx=ε(p),thenitholdsforallx∈S.
Smustbenon-empty.Hereisanexample,whereweconsiderfinite
This is known as the Drinker Paradox: in every pub there is a
setsgivenasfinitelists:
person a such that if a drinks then everybody drinks. Here S is
find :: [x] -> J Bool x thesetofpeopleinthepub,andp(x)meansthatxdrinks,andwe
find [] p = undefined calculate a with the selection function as a = ε(p). A selection
functionfortheuniversalquantifierofafinitesetcanbedefinedin Ofcoursethedefinitionofargsupisequivalentto
Haskellasfollows:
argsup p = if p True > p False then True else False
findnot :: [x] -> J Bool x
whichisperhapsmorenaturalbutlesslazy.Ifwewantourgoods
findnot [] p = undefined
tobegivenasalist,wecaninsteaddefine
findnot [x] p = x
findnot (x:xs) p = if p x then findnot xs p else x argsup :: [x] -> J Int x
argsup [] p = undefined
Noticethatthissatisfies
argsup [x] p = x
findnot = find.not argsup (x:y:zs) p = if p x < p y
then argsup (y:zs) p
andthatthefunctionforeverydefinedabovesatisfies
else argsup (x:zs) p
forevery = overline.findnot
This can be made more efficient by avoiding re-evaluations of p.
We now consider “predicates” that give numbers rather than Moreover,iftherangeofpisnotthesetofallintegers,butjusta
booleantruthvalues(sometimesknownasobjectivefunctions).For finiterange,suchas−1,0,1,thenthefollowingisamoreefficient
example, the predicate may assign prices to goods. Given such a algorithm,whichstopswhenthemaximumvalue1isreached,and
predicate,wemaywishto switchestoaspecializedalgorithmwhenthevalue0isreached:
1. findthepriceofthemostexpensivegood—thisisdonebya argsup :: [x] -> J Int x
quantifier,calledsup, argsup [] p = undefined
2. find the most expensive good — this is done by a selection argsup (x:xs) p = f xs x (p x)
function,calledargsup. where f xs a 1 = a
f [] a r = a
Ofcourse,theresultoftheselectionfunctionisambiguouslyde-
f (x:xs) a (-1) = f xs x (p x)
fined, because there may be more than one good with the high-
f xs a 0 = g xs
estprice(justastheremaybemorethanoneelementsatisfyinga
where g [] = a
givenboolean-valuedpredicate,andwechoseonearbitrarilywith
g (x:xs) | p x == 1 = x
theabovealgorithms).
| otherwise = g xs
This should be compared with the Maximum-Value Theorem,
whichsaysthatanycontinuousfunctionp: [0,1] → Rattainsits
maximumvalue.Thismeansthatthereisa∈[0,1]suchthat Infimacanhehandledbymirroringthisalgorithm,oralternatively
byreductiontosuprema,wheretheinvolution\x -> -xplaysthe
supp=p(a).
roleofnegationinthiscontext:
However,theproofisnon-constructive,anditisknownthatthere
arginf :: [x] -> J Int x
is no computable selection function argsup that calculates a =
argsup(p)(butthesupremumquantifiersup: ([0,1] → R) → R arginf xs p = argsup xs (\x -> - p x)
is known to be computable). This can also be compared to the Thesetwofunctionswillbeusefulfortwo-playergamesinwhich
Mean-ValueTheorem,whichsaysthatforsomea∈[0,1], therecanbeadraw.
Z
p=p(a).
3. Productsofselectionfunctions
Againthisacannotbefoundfrompusinganalgorithm.Similarly Wefirstconsiderbinaryproductsofselectionfunctions,andthen
theDrinkerParadoxcanbewritten iteratethem(in)finitelyoften,obtainingthefunctionaldiscussedin
Section1.
∀(p)=p(a),
andfindingelementsinsetscorrespondsto 3.1 Binaryproduct
∃(p)=p(a). Inordertomotivateourconstruction,considerthefollowingvari-
ationoftheDrinkerParadoxdiscussedabove:ineverypubthere
We have already seen that we can find a as a = ε(p) if the areamana andawomana suchthatifa buysadrinktoa
0 1 0 1
ranges of the universal and existential quantifiers are finite (and theneverymanbuysadrinktosomewoman.Ifthesetsofmenand
we’ll go beyond the finite case below). The general equation we womenareX andX respectively,andifwedefinethecombined
0 1
areconsideringhereisthus quantifierφ=∀⊗∃by
φ(p)=p(a),
φ(p)=(∀x ∈X ∃x ∈X p(x ,x )),
0 0 1 1 0 1
whereinfavourablecircumstancesacanbecalculatedas
then this can be formalized by saying that, for a suitable pair
a=ε(p) a=(a0,a1)∈X0×X1,
forasuitableselectionfunctionεthatworksforallpredicatesp. φ(p)=p(a).
Continuing the discussion about prices of goods, in the next
Ourobjectiveistocalculatesuchapaira.
example we artificially assume that the only two goods are True
Thekeyobservationisthatwehaveselectionfunctionsforthe
andFalse,andthatournumbersareintegers:
quantifiers ∀ and ∃, say ε and ε , and that what we need is a
0 1
argsup :: J Int Bool suitablecombinedselectionfunctionε=ε ⊗ε forthecombined
0 1
argsup p = p True > p False quantifierφ = ∀⊗∃.Wedefinecombinationsofquantifiersand
of selection functions in such a way that they commute with the
sup :: K Int Bool above monad morphism, where the combinator is written ⊗ for
sup = overline argsup bothquantifiersandselectionfunctions.Inotherwords:
Ifε isaselectionfunctionforthequantifierφ fori=0,1, adifferentprogramforeachnisrequired.Thislimitationcanbe
i i
thenε = ε ⊗ε isaselectionfunctionforthequantifier overcome if we restrict ourselves to the particular case in which
0 1
Q
φ=φ ⊗φ . X =XforeveryiandsomefixedX.Then X amountsto
0 1 i i<n i
thetypeoffinitelistsoflengthn,andwewriteanalgorithmthat
Itiseasytodefinetheproduct⊗ofquantifiers,generalizingfrom
worksforlistsofanylength.
theaboveexample,whereφ=φ ⊗φ forφ =∀andφ =∃:
0 1 0 1 Wefirstneedtoconsidertheparticularcaseofthebinaryprod-
(φ0⊗φ1)(p)=φ0(λx0.φ1(λx1.p(x0,x1))). uct with types x0 = x and x1 = [x] for a given type x. Then
a pair (a ,a )::(x ,x ) can be coded as the list (a :a )::[x].
Thedefinitionoftheproductofselectionfunctionsisabitsubtler: 0 1 0 1 0 1
Withthesechoicesandcoding,theabovebinary-productprogram
(ε0⊗ε1)(p) = (a0,a1) canberewrittenas
where a =ε (λx .ε (λx .p(x .x )))
0 0 0 1 1 0 1 otimes :: J r x -> J r [x] -> J r [x]
a1 =ε1(λx1.p(a0,x1)). otimes e0 e1 p = a0:a1
where a0 = e0(\x0 -> overline e1(\x1 -> p(x0:x1)))
Whatweneedtocheckisthat
a1 = e1(\x1 -> p(a0:x1))
ε ⊗ε =ε ⊗ε ,
0 1 0 1
Thisisnowinasuitableformforiteration:
whichamountsto
bigotimes :: [J r x] -> J r [x]
ifφ =ε fori=0,1,thenφ ⊗φ =ε ⊗ε .
i i 0 1 0 1 bigotimes [] = \p -> []
Thisisaroutineverificationthatthereaderisencouragedtoper- bigotimes (e:es) = e ‘otimes‘ bigotimes es
form for the sake of understanding (and that is performed in the
givenreferences).Comingbacktoourmotivatingexample,there- Expandingthedefinitions,thisisthesamealgorithmgiveninSec-
quiredmanandwomancanbecalculatedwiththeformula tion1.Althoughwehavemotivatedthisalgorithmbyconsidering
finitelists,itdoesmakesenseforinfiniteliststoo,asweshallsee
(a ,a )=(ε ⊗ε )(p),
0 1 0 1 induecourse.
whereε andε areselectionfunctionsforthequantifiers∀and∃
0 1
respectively.
4. Playinggames
Thebinaryproductofselectionfunctionscanbeimplemented
as Wefirstshowthatproductsofselectionfunctionscomputeoptimal
plays and strategies. We then generalize the product of selection
otimes :: J r x0 -> J r x1 -> J r (x0,x1)
functions in order to account for history dependent games, and
otimes e0 e1 p = (a0,a1)
giveconciseandefficientimplementationsofTic-Tac-Toeandn-
where a0 = e0(\x0 -> overline e1(\x1 -> p(x0,x1)))
Queensasillustrationsofthetechniques.
a1 = e1(\x1 -> p(a0,x1))
We leave the implementation of the binary product of quantifiers 4.1 Optimaloutcomes,playsandstrategies
as an exercise (but later we shall implement the binary product
Asafirstexample,consideranalternating,two-persongamethat
for all monads, which will apply to the selection monad and the
finishesafterexactlynmoves,withoneoftheplayerswinning.The
continuationmonadinparticular).
i-thmoveisanelementofthesetX andthegameisdefinedbya
i
Q
3.2 Iteratedproduct predicatep: i<nXi →Rwith
GivenasequenceofsetsX0,X1,...,Xn,...,definetheproduct R=Bool,
Q
X byinductiononnas
i<n i
thattellswhetherthefirstplayer,EloiseplayingagainstAbelard,
YXi ={()}, Y Xi =X0×YXi+1. winsagivenplayx = (x0,...,xn−1) ∈ Qi<nXi.ThenEloise
i<0 i<n+1 i<n hasawinningstrategyforthegamepifandonlyif
Informally,
∃x ∈X ∀x ∈X ∃x ∈X ∀x ∈X ···p(x ,...,x ).
Y 0 0 1 1 2 2 3 3 0 n−1
X =X ×···×X .
i 0 n−1
Ifwedefine
i<n
(
Foreachnwedefineafunction ∃ ifiiseven,
O: YJRXi →JRYXi, φi = ∀XXii ifiisodd,
i<n i<n then this condition for Eloise having a winning strategy can be
byinductionas equivalentlyexpressedas
O O O
ε =λp.(), ε =ε ⊗ ε . !
i i 0 i+1 O
i<0 i<n+1 i<n φi (p).
Finiteproductsofquantifierscanbedefinedinthesameway,and i<n
thefollowingequationholds,byinduction: Moregenerally,thisvaluegivestheoptimaloutcomeofthegame,
O O which takes place when all players play as best as they can. In
ε = ε .
i i thisexample,theoptimaloutcomeisTrueifEloisehasawinning
i<n i<n strategy,andFalseifAbelardhasawinningstrategy.
Ofcourse,theproductsareofquantifiersintheleft-handsideand The following is proved in the paper [8], which also gives
ofselectionfunctionsintheright-handside. formaldefinitionsofthegametheoreticterminology.Supposeeach
In dependently typed languages such as Agda, one can write quantifier φ has a selection function ε (thought of as a policy
i i
a single product program that works for every n, but in Haskell functionforthei-thmove).
1. Thesequence appropriately:
!
(φ ⊗φ )(p)=φ (λx .φ (x )(λx .p(x ,x ))).
O 0 1 0 0 1 0 1 0 1
a=(a ,...,a )= ε (p)
0 n−1 i
Similarly, given a selection function and a family of selection
i<n
functions,
isanoptimalplay.
ε ∈JRX , ε : X →JRX ,
Thismeansthatforeverystagei<nofthegame,themovea 0 0 1 0 1
i
isoptimalgiventhatthemovesa0,...,ai−1havebeenplayed. wedefinetheirhistory-dependentproduct
Q
2. Thefunctionfk : i<kXi →Xkdefinedby (ε0⊗ε1)(p) = (a0,a1)
nO−1 ! ! where a0 =ε0(λx0.ε1(x0)(λx1.p(x0.x1)))
f (a)= ε (λx.p(a++x))
n i a =ε (a )(λx .p(a ,x )),
1 1 0 1 0 1
i=k 0
whereitisunderstoodthatε (x ) = ε (x ).Andthenagainwe
isanoptimalstrategyforplayingthegame. 1 0 1 0
have
Thismeansthatifthesequenceofmovesa = (a ,...,a )
0 k−1 ε ⊗ε =ε ⊗ε .
have been played, then a = f (a) is at optimal move at 0 1 0 1
k k
stagek. This amounts to saying that if ε0 is a selection function for the
Here k < n − 1, and x ∈ Qn−1X , and a++x is the quantifierφ0,andifε1(x0)isaselectionfunctionforthequantifier
i=k i φ (x )foreveryx ∈X ,thenε ⊗ε isaselectionfunctionfor
concatenationofthesequencesa = (a ,...,a )andx = 1 0 0 0 0 1
0 k−1 thequantifierφ ⊗φ .
(x ,...,x ),andthesubscript0picksthefirstelementof 0 1
k n−1 Wecaniteratethisifwearegivenasequenceofhistorydepen-
thelistcalculatedinsidethebrackets.
dentselectionfunctions
Asasecondexample,wechoose Y
ε : X →JRX .
n i n
R={−1,0,1}
i<n
instead, with the convention that −1 means that Abelard wins, 0 Wedothisbyinduction,usingthebinaryhistorydependentproduct
means that the game is a draw, and 1 that Eloise wins. Because intheinductionstep:
EloiseandAbelardwanttomaximizeandminimizetheoutcome
O
of the game respectively, we replace the existential and universal εi=λp.(),
quantifierssupandinfrespectively, i<0
( O O
sup ifiiseven, εi=ε0()⊗λx0. (λ(x1,...,xi).εi+1(x0,...,xi)).
φi = inf Xi ifiisodd. i<n+1 i<n
Xi
This can be written in Haskell as follows, if we trivialize the
N
Theoptimaloutcomeisstillcalculatedas i<nφi,whichinthis dependentproductsasabove:
caseamountsto
otimes :: J r x -> (x -> J r [x]) -> J r [x]
sup inf sup inf ···p(x0,...,xn−1), otimes e0 e1 p = a0 : a1
x0∈X0x1∈X1x2∈X2x3∈X3 where a0 = e0(\x0->overline(e1 x0)(\x1->p(x0:x1)))
and is 1 if Eloise has a winning strategy, −1 if Abelard has a a1 = e1 a0 (\x1 -> p(a0:x1))
winning strategy, and 0 otherwise. Moreover, the above formulas
forcomputingoptimaloutcomes,playsandstrategiesapply. bigotimes :: [[x] -> J r x] -> J r [x]
bigotimes [] = \p -> []
4.2 Historydependentgames
bigotimes (e:es) =
Inmostsequentialgamesofinterestandthatoccurinpractice,the e[] ‘otimes‘ (\x->bigotimes[\xs->d(x:xs) | d<-es])
setofallowedmovesatagivenstagedependsonthemovesplayed
at the previous stages. The simplest case is that of a two-move 4.3 Implementationofgamesandoptimalstrategies
game. We assume that we have sets of moves X0 and X1. Once To define a sequential game, we need to define a type R of out-
amovex0 ∈ X0 hasbeenplayed,theallowedmovesformaset comes,atypeMoveofmoves,apredicate
S ⊆ X thatdependsonx .Wewanttoaccountforsituations
suxc0has 1 0 p :: [Move] -> R
∀x ∈X ∃x ∈S p(x ,x ). thatgivestheoutcomeofaplay,and(history-dependent)selection
0 0 1 x0 0 1
Forexample,ineverypubthereareamana andawomana older functionsforeachstageofthegame:
0 1
than a0 such that if a0 buys a drink to a1, then every man buys epsilons :: [[Move] -> J R Move]
a drink to an older woman. Here S is the set of women older
thanx .Thiscanbeformalizedbycoxn0sideringtwoquantifiers,the Once this is done, we can compute optimal plays, optimal out-
0
secondofwhichhasaparameter: comes, and optimal strategies with the mathematical formulas
givenabove:
φ ∈KRX , φ : X →KRX .
0 0 1 0 1
optimalPlay :: [Move]
Inourrunningexample, optimalPlay = bigotimes epsilons p
φ (q) = ∀x ∈X q(x ),
0 0 0 0
optimalOutcome :: R
φ (x )(q) = ∃x ∈S q(x ).
1 0 1 x0 1 optimalOutcome = p optimalPlay
Theirhistory-dependentproductisdefinedasthehistory-freeprod-
uct considered before, taking care of instantiating the parameter optimalStrategy :: [Move] -> Move
optimalStrategy as = head(bigotimes epsilons’ p’) standardprogrammingexercise,butweincludethedefinitionlater
where epsilons’ = drop (length as) epsilons forthesakeofcompleteness.
p’ xs = p(as ++ xs) Nextwedefineafunctionoutcomesuchthat,givenaplayer,a
play(thatis,alistofmoves),andaboard,producestheboardthat
Notice that all playersuse the same strategy function. To be pre-
resultsafterplayingthemovesinanalternatingfashion.Ifatsome
cise, because the notion of player is not part of our definition of
pointoneplayerwins,thentheremainingmovesareignoredand
sequentialgame,thestrategysayswhatmoveshouldbeplayedat
theboardisunchanged:
stagekgiventhemovesatstagesi<k.Thesethreedefinitionsap-
plytobothhistory-freeandhistory-dependentgamesandproducts outcome :: Player -> [Move] -> Board -> Board
ofselectionfunctions. outcome whoever [] board = board
outcome X (m : ms) (x, o) =
4.4 Finitegamesofunboundedlength
if wins o then (x, o)
Sofarwehavediscussedfiniteproducts,andhencegames,offixed else outcome O ms (insert m x, o)
length.Inordertoaccountforfinitegamesofunboundedlength, outcome O (m : ms) (x, o) =
weuseinfinitelazylists,andweassumethatthepredicatepscans if wins x then (x, o)
the list of moves until the game ends and produces an outcome. else outcome X ms (x, insert m o)
Of course, for this we need that every sequence of moves does
Thenthepredicatethatdefinesthegameisobtainedbycomputing
eventuallyleadtotheendofthegameinafinitenumberofmoves.
theoutcomeoftheplaystartingfromtheemptyboard.Weassume
Theonlyexplicitlygiveninfinitelazylistinthespecificationofa
thatplayerXstarts,asusual:
gameisthelistepsilonsofpolicyfunctionsforeachstageofthe
game. p :: [Move] -> R
p ms = value(outcome X ms ([],[]))
4.5 Tic-Tac-Toe
Finally, we need to the define the selection functions, or policy
WenowconsiderTic-Tac-Toeasanillustrationoftheabovetech-
functions,foreachstageofthegame.Asdiscussedabove,because
niques,butweemphasizethattheideasareverygeneralandapply
the player X wants to maximize the outcome of the game, and O
toawidevarietyofsequentialgames.Thetypeofplayersis
wantstominimizeit,weuseselectionfunctionsforthesupremum
data Player = X | O andinfimumquantifiers,definedabove.Theseselectionfunctions
arehistory-dependent,wherethehistoryhisthesequenceofmoves
Theoutcomesare1(firstplayerwins),-1(secondplayerwins)and
playedsofar,andtheychoosemovesamongthosethathaven’tbeen
0(draw).Werepresentthembyintegers:
playedyet:
type R = Int
epsilons :: [[Move] -> J R Move]
Thepossiblemovesare epsilons = take 9 all
where all = epsilonX : epsilonO : all
0 1 2
epsilonX h = argsup ([0..8] ‘setMinus‘ h)
3 4 5
epsilonO h = arginf ([0..8] ‘setMinus‘ h)
6 7 8
Thefunction
Soagainwerepresentmovesbyintegers:
setMinus :: Ord x => [x] -> [x] -> [x]
type Move = Int
returns a list with all elements that are in the first list but not in
Althoughtheconceptofagameboarddoesn’tfeatureexplicitlyin
the second one. And that’s it, apart from the standard definition
ourspecificationofasequentialgame,itisconvenienttointroduce
of set-theoretical operations, which are routine, but are given in
itinourimplementation:
Section4.7belowforthesakeofcompleteness.
type Board = ([Move], [Move]) Totesttheprogram,weadd
The components of the pair are the sets of moves played by X main :: IO ()
andOrespectively.Werepresentthesesetsassortedlistswithout main =
repetitionsforefficiency.Asetofmoveswinsifitcontainsarow, putStr ("An optimal play for Tic-Tac-Toe is "
a column or a diagonal, and we use this to define the value of a ++ show optimalPlay ++ "\nand the optimal outcome is "
board: ++ show optimalOutcome ++ "\n")
wins :: [Move] -> Bool CompilingthiswiththeGlasgowHaskellcompileras
wins =
someContained [[0,1,2],[3,4,5],[6,7,8], $ ghc --make -O2 TicTacToe.hs
[0,3,6],[1,4,7],[2,5,8],
andrunning
[0,4,8],[2,4,6]]
$ time ./TicTacToe
value :: Board -> R
under the operating system Ubuntu/Debian 9.10 in a 2.13GHz
value (x,o) | wins x = 1
machine,weget:
| wins o = -1
| otherwise = 0 An optimal play for Tic-Tac-Toe is [0,4,1,2,6,3,5,7,8]
and the optimal outcome is 0
Herethefunction
someContained :: Ord x => [[x]] -> [x] -> Bool real 0m1.721s user 0m1.716s sys 0m0.004s
satisfiessomeContained xss ys = Trueifandonlyifsomelist Thismeansthat,asiswellknown,ifthetwoplayersplayasbest
xsinthelistxsshasallelementsoccurringinthelistys.Thisisa as they can, the game is a draw. There are many optimal plays.
Thecomputedonedependsonwhichselectionfunctionswehave $ ghci --make -O2 NQueens.hs
chosenforoursupremumandinfimumquantifiers.Inpictures,the $ time ./NQueens
computedoptimalplayis:
andweget:
X X X X
An optimal play for 8-Queens is [0,4,7,5,2,6,1,3]
O O
and the optimal outcome is True
real 0m0.011s user 0m0.012s sys 0m0.000s
X X O X X O X X O
ThefactthattheoptimaloutcomeisTruemeansthattheoptimal
O O O O playisindeedasolutionofthe8-Queensproblem.Withn = 12
X X the solution [0,2,4,7,9,11,5,10,1,6,8,3] is computed in five
seconds. It should be apparent that many other standard games
andsearchproblemscanbeconciselyexpressedandsolvedinthis
X X O X X O X X O
formalismusingthesamepattern.
O O X O O X O O X
X X O X O X 4.7 Appendix
4.6 n-Queens For the sake of completeness, so that the reported experiments
can be reproduced by the readers, with similar run-time results
Wecansolvethen-Queenspuzzleusingthesameideas.Thistime
in similar machines, we include the routine code for finite sets
this is a 1-player game, but again the number of players is not
representedassortedlistswithoutrepetitionsusedabove:
explicit in the formalization of the problem and its solution. We
adoptthefollowingconventions: contained :: Ord x => [x] -> [x] -> Bool
contained [] ys = True
1. Asolutionisapermutationof[0..(n−1)],whichtellswhere
contained xs [] = False
eachqueenshouldbeplacedineachrow.
contained (us@(x : xs)) (y : ys)
2. Amoveisanelementof[0..(n−1)],sayinginwhichcolumnof | x == y = contained xs ys
thegivenrow(=stageofthegame)thequeenshouldbeplaced. | x >= y = contained us ys
| otherwise = False
Let’ssayweconsiderthestandardchessboard:
n = 8 someContained :: Ord x => [[x]] -> [x] -> Bool
someContained [] ys = False
The following should be self-explanatory given the above devel-
someContained xss [] = False
opment and assuming familiarity with the formulation of the n-
someContained (xs : xss) ys
Queensproblem:
= contained xs ys || someContained xss ys
type R = Bool
type Coordinate = Int insert :: Ord x => x -> [x] -> [x]
type Move = Coordinate insert x [] = [x]
type Position = (Coordinate,Coordinate) insert x (vs@(y : ys))
| x == y = vs
attacks :: Position -> Position -> Bool | x < y = x : vs
attacks (x, y) (a, b) = | otherwise = y : insert x ys
x == a || y == b || abs(x - a) == abs(y - b)
delete :: Ord x => x -> [x] -> [x]
valid :: [Position] -> Bool delete x [] = []
valid [] = True delete x (vs@(y : ys))
valid (u : vs) = | x == y = ys
not(any (\v -> attacks u v) vs) && valid vs | x < y = vs
| otherwise = y : delete x ys
p :: [Move] -> R
p ms = valid(zip ms [0..(n-1)]) setMinus :: Ord x => [x] -> [x] -> [x]
setMinus xs [] = xs
epsilons :: [[Move] -> J R Move] setMinus xs (y : ys) = setMinus (delete y xs) ys
epsilons = replicate n epsilon
where epsilon h = find ([0..(n-1)] ‘setMinus‘ h) 5. TheTychonoffTheorem
Andthat’sit.Wetestthisasabove: Thissectionisaboutthecloseconnectionofsomecomputational
and topological ideas, with applications to computation. For the
main :: IO ()
purposes of this exposition, it is not required to know what the
main =
topological terms space, compact, continuous, countably based,
putStr ("An optimal play for " ++ show n
andHausdorff mean.Rather,thereadersshouldregardtopologyas
++ "-Queens is "
aforeignlanguage,andusethefactsstatedbelowasadictionary
++ show optimalPlay
betweencomputationalandtopologicalnotions.Computer-Science
++ "\nand the optimal outcome is "
Land readers interested in learning the language can start from
++ show optimalOutcome ++ "\n")
theintroductorytext[17],butthisisnotnecessaryinordertoget
Wethenrun aroundinourguidedtourtoTopologyLand.
5.1 AnexcursiontoTopologyLand 4. Any non-empty exhaustible set is a computable image of the
Cantorspace.
Callaset
Thisisprovedin[7],whichdevelopsmoreexamples.Noticethat
1. searchableifithasacomputableselectionfunction,and
we have replaced compact sometimes by searchable and some-
2. exhaustibleifithasacomputableboolean-valuedquantifier. timesbyexhaustible(andsometimesbyboth).Wedidthisdelib-
erately,inordertogetthefollowingsouvenirfromourtopological
Itwasshownin[7]that
excursion:
Exhaustiblesetsaretopologicallycompact. Non-emptyexhaustiblesetsaresearchable.
Here we are implicitly assuming that we are dealing only with Thisworksasfollows:ifthesetK isnon-emptyandexhaustible,
setsoftotalelements.Thesituationforsetsthatincludepartialor then it is a computable image of the Cantor space by (4), and
undefinedelementsissubtlerandwereferthereaderto[7].Bythe because the Cantor space is searchable by (1) and (2), the set K
development of Section 2, using the monad morphism, we know is searchable by (3). This is computationally interesting, because
thatsearchablesetsareexhaustible,andhencesearchablesetsare it says that if we have a search procedure that answers yes/no
compact too. The above quoted fact is related to the well-known (givenbyaquantifier),thenwecanautomaticallygetaprocedure
factthat thatgiveswitnesses(givenbyaselectionfunction).Moreover,the
selection function can be obtained by a higher-type functional,
Computablefunctionalsaretopologicallycontinuous.
whichcanbewritteninHaskellwiththefollowingtype:
Thisissoevenfromapurelyoperationalpointofview[4],without selectionFromQuantifier :: K Bool x -> J Bool x
consideringanydenotationalsemanticssuchasScottdomains.A
widelyquotedtopologicalsloganisthat Thedefinitionandtheargumentthatitworksarerathercomplicated
andusenon-trivialrecursion-theoreticandtopologicaltechnology,
Infinitecompactsetsbehave,inmanyinterestinganduseful andinterestedreadersarereferredto[7].
ways,asiftheywerefinite. Wenowgivesomeindicationsofhowtheaboveworks,andde-
velopsomeexamples.ThefiniteandcountablyinfiniteTychonoff
This matches computational intuition, because the ability to ex-
Theoremisimplementedbythehistory-freeversionbigotimesof
haustivelysearchaninfiniteset,algorithmicallyandinfinitetime,
theproductofselectionfunctions.Henceaselectionfunctionfor
is indeed a computational sense in which the set behaves as if it
theCantorspaceisgivenby
werefinite.Itmayseemsurprisingatfirstsightthattherearesuch
sets,butthiswasknowninthe1950’sorbefore[13,14],andwe findCantor :: J Bool [Bool]
shallseesomeexamplesshortly.Wealsoneedtomentionthatin findCantor = bigotimes (repeat findBool)
ourcomputationalsetting:
Weshallrunanexampleinamoment.Wenowimplementthefact
Sets of total elements form countably based Hausdorff thatcomputableimagesofsearchablesetsaresearchable:
spaces. image :: (x -> y) -> J r x -> J r y
image f e = \q -> f(e(\x -> q(f x)))
Here we assume that any two equivalent total elements are iden-
tified (for example, the strict and non-strict constant function This works as follows. Suppose that f :: x -> y is given and
Int -> Intareconsideredtobethesametotalelement). thate :: J r xisaselectionfunctionforasetS ⊆ x,andlet
Thepapers[5,7]explorewhathappensifonelooksattheorems f(S)={f(s)|s∈S}⊆ybetheimageofS.Givenapredicate
intopologyandappliesthisdictionary.Eventheoremsthatareat q :: y -> r, we wish to find s ∈ S such that q(s) = True.
the core of topology and analysis turn out to be computationally Thegivenalgorithmfirstfindsxsuchthatq(f x) = True,using
relevant: theselectionfunctione,andthenappliesftoit,givingthedesired
result.
1. Finitesetsarecompact,andhenceforexamplethebooleansare
compact. 5.2 Decidingequalityoffunctionals
2. Arbitrary products of compact sets are compact (Tychonoff As an application, perhaps contradicting common wisdom, we
Theorem). writeatotal(!)functionalthatdecideswhetherornottwogivento-
Hencethespaceofinfinitesequencesofbooleansiscompact. talfunctionals(Integer -> Bool) -> zareequivalent,wherez
ThisisknownastheCantorspace,asitistopologicallyisomor- isanytypewithgivendecidableequality:
phic(orhomeomorphic)tothefamousCantorThird-Middleset equal :: Eq z => ((Integer -> Bool) -> z)
intherealline. -> ((Integer -> Bool) -> z) -> Bool
3. Continuousimagesofcompactsetsarecompact.
equal f g = foreveryFunction(\u->f u == g u)
4. Anynon-empty,countablybased,compactHausdorffspaceis
acontinuousimageoftheCantorspace. This doesn’t contradict computability theory, which correctly as-
serts that, for example, equality of functions Integer -> Bool
Applyingthedictionary,weget: isnotdecidable.Agrammarthatsinglesoutinfinitelymanytypes
thathavedecidableequalityisprovidedin[7].
1. Finitesetsaresearchable,andhenceforexamplethebooleans
To complete this definition, we first faithfully code functions
aresearchable.
Integers->Boolaslazylistsbystoringnon-negativeandnega-
2. Finite and countably infinite products of searchable sets are tiveargumentsatevenandoddindicesrespectively:
searchable.
code :: (Integer -> Bool) -> [Bool]
HencetheCantorspaceissearchable.
code f = [f(reindex i)| i<-[0..]]
3. Computable images of searchable/exhaustible sets are search- where reindex i | even i = i ‘div‘ 2
able/exhaustible. | otherwise = -((i+1)‘div‘ 2)
Butactuallyweareinterestedintheoppositedirection: 5.3 Uniformcontinuityandthefanfunctional
decode :: [Bool] -> (Integer -> Bool) Readers unfamiliar with topology and its relation to computation
decode xs i | i >= 0 = xs ‘at‘ (i * 2) arelikelytobepuzzledregardingtheabovedecisionprocedurefor
| otherwise = xs ‘at‘ ((-i * 2) - 1) equalityoffunctions,andmoregenerallyuniversalquantification
overinfinitespaces.Whatisgoingon?Hereisanindication.
at :: [x] -> Integer -> x Functionsf :: [Bool] -> zarecontinuous.Ifzistopologi-
at (x:xs) 0 = x callydiscrete(hasequality),thismeansthatforeveryinputa,there
at (x:xs) (n+1) = at xs n isanindexndependingona,suchthattheanswerdoesn’tdepend
onpositionsofawithindicesi≥n.Thisisintuitivelyclearfrom
Becausethespaceoftotalinfinitesequences[Bool]issearchable
acomputationalpointofview,andcanberigorouslyproved(see
by the computational Tychonoff Theorem, and because its image
e.g. [4]). Now, the Cantor space is compact, and there are theo-
underthecomputablefunctiondecodeisthesetoftotalfunctions
remsintopologythatsaythat,inmanycases,continuousfunctions
Integer -> Bool, this set of total functions is searchable and
definedoncompactspacesareuniformlycontinuous.Inourcase,
henceexhaustible:
this means that that there is a single index n, independent of the
findFunction :: J Bool (Integer -> Bool) input,suchthatthefunctionf :: [Bool] -> zdoesn’tlookat
findFunction = image decode findCantor indicesi ≥ ninordertoproducetheoutput.Anotherwayofsay-
forsomeFunction :: K Bool (Integer -> Bool) ingthisisthatiftwoinputsaandbofthefunctionfagreeinthe
forsomeFunction = overline findFunction firstnpositions,thentheyproducethesameoutput.Thiscriterion
foreveryFunction :: K Bool (Integer -> Bool) can be coded in Haskell, and hence such an n can be computed.
foreveryFunction p = not(forsomeFunction(not.p)) Thefunctionalthatcomputesitiscalledthefanfunctional,andis
knownsincethe1950’sorevenearlier[14]:
Thiscompletesallingredientsneededtodefinethefunctionequal.
Hereisanexperiment,wherethefunctioncisacoercion: fan :: Eq z => ([Bool] -> z) -> Int
fan f = least(\n -> forevery(\a -> forevery(\b ->
c :: Bool -> Integer
agree n a b --> (f a == f b))))
c False = 0
c True = 1
least :: (Int -> Bool) -> Int
least p = if p 0 then 0 else 1+least(\n -> p(n+1))
f, g, h :: (Integer -> Bool) -> Integer
f a = c(a(7 * c(a 4) + 4 * (c(a 7)) + 4))
forsome, forevery :: K Bool [Bool]
g a = c(a(7 * c(a 5) + 4 * (c(a 7)) + 4))
forsome = overline findCantor
h a = if not(a 7)
forevery p = not(forsome(not.p))
then if not(a 4) then c(a 4) else c(a 11)
else if a 4 then c(a 15) else c(a 8)
agree :: Int -> [Bool] -> [Bool] -> Bool
Areanytwoofthesethreefunctionsequal?Whenwerunthis,using agree n a b = take n a == take n b
theinterpreterthistime,weget:
(-->) :: Bool -> Bool -> Bool
$ ghci Tychonoff.hs
p --> q = not p || q
...
Ok, modules loaded: Main. Hereisatrivialexample:
*Main> :set +s
*Main> fan(\a -> a !! 5 && a !! 6)
*Main> equal f g
7
False
(0.02 secs, 4274912 bytes) However, we are not interested in computing the fan functional.
*Main> equal g h What is relevant is that once we know the modulus of uniform
False continuity n, it is enough to inspect 2n cases to figure out the
(0.01 secs, 0 bytes) completebehaviourofthefunction.
*Main> equal f h Ifthereisanymagicintheabovealgorithmforquantifyingover
True theCantorspaceandhencedecidingequalityoffunctionsdefined
(0.00 secs, 0 bytes) on the Cantor space, it amounts to the facts that (1) this n is not
explicitly calculated by the quantification procedure (although it
(Wehavenocluewhythelastcomputationisreportedtotakezero
canbecalculatedwiththefanfunctionalthatusesthisprocedure),
bytes!) These examples are somewhat trivial, although probably
and (2) very often, a small portion of the 2n cases actually need
puzzling.Anon-trivialapplicationofquantificationovertheCantor
tobecheckedinthequantificationprocedure(thishastodowith
spaceisgivenin[16].Thisdevelopsanalgorithmfornumericalin-
lazy evaluation). If we move from [Bool] to [Integer], then
tegration,whererealnumbersarerepresentedasinfinitesequences
compactnessanduniformcontinuityfail,andmoreoverequalityof
ofdigits.Hencetherearenoround-offerrorsintheproducedre-
functions(Integer -> Integer) -> zisnolongerdecidable.
sults, which can be computed to arbitrary precision with guaran-
teedaccuracy.Comingbacktoourtrivialexample,wheredofand
6. Monads
gdiffer?
Itturnsoutthatthefunctionimagedefinedaboveisthefunctorof
*Main> take 11 (code (findFunction(\u->g u /= h u)))
amonad[8].Theunitis
[True,True,True,True,True,True,
True,True,True,True,False] singleton :: x -> J r x
(0.05 secs, 3887756 bytes) singleton x = \p -> x
Webelievethattheseideasopenupthepossibilityofnew,useful Itimplementsthefactthatsingletonsaresearchable.Themultipli-
toolsforautomaticprogramverificationandbugfinding. cationis
bigunion :: J r (J r x) -> J r x sequence :: Monad m => [m a] -> m [a]
bigunion e = \p -> e(\d -> overline d p) p sequence = foldr mcons (return [])
where mcons p q =
Itimplementsthefactthattheunionofasearchablesetofsearch-
p >>= \x->q >>= \y->return (x:y)
ablesetsissearchable(butitactuallysatisfiesamoregeneralspec-
ificationinvolvinggeneralizedquantifiers[8]).Toseethatthemul- Thus,ourcomputationalmanifestationoftheTychonoffTheorem
tiplicationbehavesasclaimed,assumethattheselectionfunctione is already in the Haskell standard prelude, and becomes immedi-
selectsoveracollectionofselectionfunctionsdforsetsS .Using atelyavailableonceonedefinestheselectionmonad.
d
the selection function e, we find a selection function d such that Here the function mcons is simply one of the versions of our
p(d p)holds,i.e.p sholdsforsomes∈S .Thenweapplythis function otimes generalized from the continuation and selection
d
selectionfunctiontop,toactuallyfindsuchs. monadstoanymonad,andcanbeequivalentlywrittenas
mcons :: Monad m => m x -> m[x] -> m[x]
6.1 Thecontinuationandselectionmonads
xm ‘mcons‘ xsm =
WenowwritethemonadsusingHaskell’sconventions,wherethe do x <- xm
above gets a bit cumbersome and probably harder to understand, xs <- xsm
asHaskellrequirestagsformonads,andhenceweneedfunctions return (x:xs)
forextractingtags(namelyquantifierandselection).Wefirst
definethecontinuationmonad: Moreover,sequenceitselfcanbeequivalentlywrittenas
sequence :: Monad m => [m x] -> m[x]
module K (K(K), quantifier, unitK, functorK, muK) where
sequence [] = return []
newtype K r x = K {quantifier :: (x -> r) -> r} sequence (xm : xms) =
do x <- xm
unitK :: x -> K r x xs <- sequence xms
unitK x = K(\p -> p x) return(x : xs)
functorK :: (x -> y) -> K r x -> K r y The history-dependent version of bigotimes also generalizes to
functorK f phi = K(\q -> quantifier phi(\x -> q(f x))) anymonad:
muK :: K r (K r x) -> K r x hsequence :: Monad m => [[x] -> m x] -> m[x]
muK phi = K(\p -> quantifier phi hsequence [] = return []
(\gamma -> quantifier gamma p)) hsequence (xm : xms) =
do x <- xm []
instance Monad (K r) where xs <- hsequence[\ys -> ym(x:ys) | ym <- xms]
return = unitK return(x : xs)
phi >>= f = muK(functorK f phi)
butthistimethisisnotinthestandardprelude.
Usingthis,wedefinetheselectionmonad: Another consequence of having a monad is the topic of Sec-
tion7,forwhichtheremarksofSection6.3arerelevant.
module J (J(J), selection, unitJ, functorJ, muJ,
module K, morphismJK) where
6.3 Thefunction(h)sequenceinmonadsotherthanJr
import K Weobservethatsequenceandhsequence,althoughdefinedfor
newtype J r x = J {selection :: (x -> r) -> x} all monads, usually don’t produce convergent computations in
monads other than J r when supplied with infinite lists. More-
morphismJK :: J r x -> K r x over,thetyperhastohavedecidableequalityforinfiniteproducts
morphismJK e = K(\p -> p(selection e p))
of selection functions to be total (topologically, it has to be dis-
crete) [8]. The termination proof is non-trivial and relies on the
unitJ :: x -> J r x
so-called bar induction principle. In particular, infinite products
unitJ x = J(\p -> x)
N
ofquantifierscannot becomputedwithsequenceor ,asalso
functorJ :: (x -> y) -> J r x -> J r y shownin[8],withacontinuityargument.
functorJ f e = J(\q->f(selection e(\x->q(f x)))) Onecaneasilyunderstandthiskindofphenomenonwiththelist
monad.Inthefinitecase,sequencecomputescartesianproducts
muJ :: J r(J r x) -> J r x inthelexicographicorder:
muJ e = J(\p -> selection(selection e
(\d -> quantifier(morphismJK d) p)) p) Prelude> sequence [[0,1],[0,1],[0,1]]
[[0,0,0],[0,0,1],[0,1,0],[0,1,1],
instance Monad (J r) where [1,0,0],[1,0,1],[1,1,0],[1,1,1]]
return = unitJ
e >>= f = muJ(functorJ f e) But now the elements of the countable cartesian product {0,1}ω
cannot be arranged in an infinite list, by Cantor’s diagonal argu-
A proof that the monad laws hold is given in [8]. There is also ment,andwhenweattempttolistthemusingsequence,wegeta
a short proof written in the dependently typed programming lan- divergentcomputation,whichinpracticeabortsforlackofmem-
guage/proofcheckerAgda[3]availableat[9]. ory:
6.2 Consequencesofhavingamonad Prelude> sequence (repeat [0,1])
*** Exception: stack overflow
Firstofall,nowthehistory-freeversionofthefunctionalbigotimes
issimplytheHaskellstandardpreludefunctionsequenceinstan- It is reassuring to see Haskell refusing to give an answer to an
tiatedtotheselectionmonad: impossiblequestion.
Description:In fact, once we define this monad in Haskell, it turns out that this amazingly versatile Therefore Haskell proves that this functional is even more versatile than chosen for our supremum and infimum quantifiers. In pictures, the .. tools for automatic program verification and bug finding. 5.3 Un