Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.
Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.
| Download
Logic of "all" + verbs + relative clauses, for a class at Indiana University
Project: moss notebooks
Views: 7252module Grand where123import Data.List4import Data.Maybe5import Control.Arrow6import Control.Monad (guard)7{-import Data.Maybe (listToMaybe,maybeToList)-}8import Data.Char (toLower)91011class Syn a where12negation :: a -> a13subterms :: a -> [Term]14cnsIn :: a -> [CN]15verbsIn :: a -> [V]16buildTermSub :: a -> a -> Maybe [(Term,Term)]17buildPVSub :: a -> a -> Maybe [(PV,PV)]18spellOut :: a -> [(Term, Term)] -> [(PV, PV)] -> a19hasNegativeMarker :: a-> Bool20212223xAsDefaultTerm :: Maybe Term -> Term24xAsDefaultTerm = fromMaybe (CNasTerm $ PCN Pos X)2526rAsDefaultPV :: Maybe PV -> PV27rAsDefaultPV = fromMaybe (PV Pos R)2829plusStrict :: (Eq a) => Maybe [a] -> Maybe [a] -> Maybe [a]30plusStrict a b = a >>= \x -> b >>= \y -> return $ nub $ x ++ y3132hunt :: (Eq a) => a -> Maybe [(a,a)] -> Maybe a3334hunt t Nothing = Nothing35hunt t (Just []) = Nothing36hunt t (Just ((uu,vv):rest))37| (t==uu) = (Just vv)38| otherwise = hunt t (Just rest)3940moveAhead :: (Eq a) => Maybe [(a,a)] -> Maybe [(a,a)] -> Bool41moveAhead Nothing xx = False42moveAhead xx Nothing = False43moveAhead (Just []) xx = True44moveAhead (Just ((uu,vv):rest)) xx45| value == (Just vv) = (moveAhead (Just rest) xx)46| value == Nothing = (moveAhead (Just rest) xx)47| otherwise = False48where value = hunt uu xx4950combineStructures xx yy =51if moveAhead xx yy == True then (plusStrict xx yy) else Nothing5253polarizedCNNegation (PCN Pos cn) = (PCN Neg cn)54polarizedCNNegation (PCN Neg cn) = (PCN Pos cn)5556-- the definition of pCNsIn is needed in Sdagleq.hs, but not elsewhere57pCNsIn (CNasTerm (PCN Pos cn)) = (PCN Pos cn)58pCNsIn (CNasTerm (PCN Neg cn)) = (PCN Neg cn)59pCNsIn (TermMaker (PV Pos v) (TermNP All n)) = pCNsIn n60pCNsIn (TermMaker (PV Pos v) (TermNP Some n)) = pCNsIn n61pCNsIn (TermMaker (PV Neg v) (TermNP All n)) = pCNsIn n62pCNsIn (TermMaker (PV Neg v) (TermNP Some n)) = pCNsIn n6364instance Syn PolCN where65negation (PCN Pos cn) = (PCN Neg cn)66negation (PCN Neg cn) = (PCN Pos cn)67subterms cn = []68cnsIn (PCN p cn) = [cn]69verbsIn (PCN p cn) = [ ]70buildTermSub (PCN p cn) (PCN p' cn') = Just []71buildPVSub (PCN p cn) (PCN p' cn') = Just []72spellOut (PCN p cn) k k' = (PCN p cn) --- THIS LINE IS QUESTIONABLE. IT'S NOT NEEDED73hasNegativeMarker (PCN Pos cn) = False74hasNegativeMarker (PCN Neg cn) = True7576instance Syn Term where77negation (CNasTerm (PCN Pos cn)) = (CNasTerm (PCN Neg cn))78negation (CNasTerm (PCN Neg cn)) = (CNasTerm (PCN Pos cn))79negation (TermMaker (PV Pos v) (TermNP All n)) = TermMaker (PV Neg v) (TermNP Some n)80negation (TermMaker (PV Pos v) (TermNP Some n)) = TermMaker (PV Neg v) (TermNP All n)81negation (TermMaker (PV Neg v) (TermNP All n)) = TermMaker (PV Pos v) (TermNP Some n)82negation (TermMaker (PV Neg v) (TermNP Some n)) = TermMaker (PV Pos v) (TermNP All n)83subterms (CNasTerm ter) = [(CNasTerm ter)]84subterms (TermMaker pv (TermNP d ter)) = (TermMaker pv (TermNP d ter)):subterms ter85cnsIn Ter1 = []86cnsIn Ter2 = []87cnsIn Ter3 = []88cnsIn Ter1bar = []89cnsIn Ter2bar = []90cnsIn Ter3bar = []91cnsIn (CNasTerm (PCN p cn)) = [cn]92cnsIn (TermMaker t n) = (cnsIn n)93hasNegativeMarker (CNasTerm (PCN Pos cn)) = False94hasNegativeMarker (CNasTerm (PCN Neg cn)) = True95hasNegativeMarker (TermMaker (PV Pos v) (TermNP All n)) = hasNegativeMarker n96hasNegativeMarker (TermMaker (PV Pos v) (TermNP Some n)) = hasNegativeMarker n97hasNegativeMarker (TermMaker (PV Neg v) (TermNP All n)) = hasNegativeMarker n98hasNegativeMarker (TermMaker (PV Neg v) (TermNP Some n)) = hasNegativeMarker n99100101verbsIn (TermMaker (PV pol ver) np) = [ver] ++ (verbsIn np)102verbsIn _ = []103104buildTermSub (TermMaker x y) (CNasTerm z) = Nothing105buildTermSub (CNasTerm (PCN Pos cn)) (CNasTerm dn) = Just [(CNasTerm (PCN Pos cn), CNasTerm dn)]106buildTermSub (CNasTerm (PCN Neg cn)) (CNasTerm (PCN Pos dn)) = Just [(CNasTerm (PCN Pos cn), CNasTerm (PCN Neg dn))]107buildTermSub (CNasTerm (PCN Neg cn)) (CNasTerm (PCN Neg dn)) = Just [(CNasTerm (PCN Pos cn), CNasTerm (PCN Pos dn))]108buildTermSub (CNasTerm zz)(TermMaker xx yy) = Nothing109buildTermSub (TermMaker v np1) (TermMaker w np2) = buildTermSub np1 np2110buildTermSub Ter1 t = Just [(Ter1, t)]111buildTermSub Ter2 t = Just [(Ter2, t)]112buildTermSub Ter3 t = Just [(Ter3, t)]113buildTermSub Ter1bar t = Just [(Ter1, negation t)]114buildTermSub Ter2bar t = Just [(Ter2, negation t)]115buildTermSub Ter3bar t = Just [(Ter3, negation t)]116buildPVSub (TermMaker xx yy) (CNasTerm zz) = Nothing117buildPVSub (CNasTerm xx) ter = Just []118buildPVSub (TermMaker vv (TermNP d t)) (TermMaker ww (TermNP e u)) =119if (d == e) then Just [(vv,ww)] else Nothing120buildPVSub Ter1 t = Just []121buildPVSub Ter2 t = Just []122buildPVSub Ter3 t = Just []123buildPVSub Ter1bar t = Just []124buildPVSub Ter2bar t = Just []125buildPVSub Ter3bar t = Just []126spellOut (CNasTerm (PCN Pos cn)) list1 list2 = xAsDefaultTerm $ lookup (CNasTerm (PCN Pos cn)) list1127spellOut (CNasTerm (PCN Neg cn)) list1 list2 = negation $ xAsDefaultTerm $ lookup (CNasTerm (PCN Pos cn)) list1128spellOut (TermMaker t n) list1 list2 = (TermMaker (rAsDefaultPV $ lookup t list2) (spellOut n list1 list2))129spellOut Ter1 list1 list2 = xAsDefaultTerm $ lookup Ter1 list1130spellOut Ter2 list1 list2 = xAsDefaultTerm $ lookup Ter2 list1131spellOut Ter3 list1 list2 = xAsDefaultTerm $ lookup Ter3 list1132spellOut Ter1bar list1 list2 = negation $ spellOut Ter1 list1 list2133spellOut Ter2bar list1 list2 = negation $ spellOut Ter2 list1 list2134spellOut Ter3bar list1 list2 = negation $ spellOut Ter3 list1 list2135136instance Syn NP where137negation (TermNP All t) = TermNP Some (negation t)138negation (TermNP Some t) = TermNP All (negation t)139--negation (TermNP Atleast t) = TermNP More (negation t)140--negation (TermNP More t) = TermNP Atleast (negation t)141subterms (TermNP All t) = subterms t142cnsIn Everyone = []143cnsIn Someone = []144cnsIn (TermNP d t) = cnsIn t145verbsIn Everyone = []146verbsIn Someone = []147verbsIn (TermNP d t) = verbsIn t148buildTermSub (TermNP d t) (TermNP e u) =149if (d == e)150then (buildTermSub t u)151else Nothing152buildPVSub xx yy = Just []153spellOut (TermNP d t) list1 list2 = (TermNP d (spellOut t list1 list2))154hasNegativeMarker (TermNP All t) = hasNegativeMarker t155hasNegativeMarker (TermNP Some t) = hasNegativeMarker t156hasNegativeMarker (TermNP Atleast t) = hasNegativeMarker t157hasNegativeMarker (TermNP More t) = hasNegativeMarker t158159instance Syn Sent where160negation (Sent All t u) = (Sent Some t (negation u))161negation (Sent Some t u) = (Sent All t (negation u))162negation (Sent Atleast t u) = (Sent More u t)163negation (Sent More t u) = (Sent Atleast u t)164subterms (Sent d t u) = (subterms t) ++ (subterms u) -- I dropped at the front [t,u] ++165subterms (Sent2 d t u t2 u2) = (subterms t) ++ (subterms u) ++ (subterms t2) ++ (subterms u2) -- I dropped [t,u,t2,u2] ++166cnsIn (Sent d t u) = (cnsIn t) ++ (cnsIn u)167cnsIn (Sent2 d t u t2 u2) = (cnsIn t) ++ (cnsIn u) ++ (cnsIn t2) ++ (cnsIn u2)168verbsIn (Sent d t u) = (verbsIn t) ++ (verbsIn u)169verbsIn (Sent2 d t u t2 u2) = (verbsIn t) ++ (verbsIn u) ++(verbsIn t2) ++ (verbsIn u2)170buildTermSub (Sent d tt uu) (Sent e vv ww) =171if (d == e) then (combineStructures (buildTermSub tt vv) (buildTermSub uu ww)) else Nothing172buildTermSub (Sent2 d tt uu tt2 uu2) (Sent2 e vv ww vv2 ww2) =173if (d == e)174then foldl1 combineStructures [(buildTermSub tt vv), (buildTermSub uu ww),(buildTermSub tt2 vv2), (buildTermSub uu2 ww2)]175else Nothing176buildPVSub (Sent d t uu) (Sent e vv ww) =177if (d == e) then (plusStrict (buildPVSub t vv) (buildPVSub uu ww)) else Nothing178buildPVSub (Sent2 d tt uu tt2 uu2) (Sent2 e vv ww vv2 ww2) =179if (d == e)180then foldl1 plusStrict [(buildPVSub tt vv), (buildPVSub uu ww),(buildPVSub tt2 vv2), (buildPVSub uu2 ww2)]181else Nothing182spellOut (Sent d t u) list1 list2 = (Sent d (spellOut t list1 list2) (spellOut u list1 list2))183spellOut (Sent2 d t u t2 u2) list1 list2 = (Sent2 d (spellOut t list1 list2) (spellOut u list1 list2) (spellOut t2 list1 list2) (spellOut u2 list1 list2))184hasNegativeMarker (Sent All t u) = and [hasNegativeMarker t, hasNegativeMarker u ]185hasNegativeMarker (Sent Some t u) = and [hasNegativeMarker t , hasNegativeMarker u ]186hasNegativeMarker (Sent Atleast t u) = and [hasNegativeMarker t, hasNegativeMarker u ]187hasNegativeMarker (Sent More t u) = and [hasNegativeMarker t, hasNegativeMarker u ]188189data Sent = Sent Det Term Term | Sent2 Det Term Term Term Term190deriving (Ord,Eq)191192instance Show Sent where193-- show (Sent d t u) = show (d) ++ " " ++ show(t) ++ " " ++ show(u)194show (Sent d (TermMaker x y) (TermMaker z w) ) = show (d) ++ " who " ++ show((TermMaker x y)) ++ " also " ++ show((TermMaker z w))195show (Sent d (TermMaker x y) (CNasTerm pcn) ) = show (d) ++ " who " ++ show((TermMaker x y)) ++ " are " ++ show((CNasTerm pcn))196show (Sent d (CNasTerm pcn) (TermMaker x y)) = show (d) ++ " " ++ show((CNasTerm pcn)) ++ " " ++ show((TermMaker x y))197show (Sent d (CNasTerm pcn) (CNasTerm pcn2)) = show (d) ++ " " ++ show((CNasTerm pcn)) ++ " are " ++ show((CNasTerm pcn2))198show (Sent2 d x y u v) = show (d) ++ " " ++ show(x) ++ " which are " ++ show(y) ++ " are also " ++ show(u) ++ " which are " ++ show(v)199200principalDet (Sent d t t') = d201converse s@(Sent All t u) = (Sent All u t)202203data NP = Everyone | Someone | TermNP Det Term | IntTermNP Det IntersectionTerm204deriving (Ord,Eq)205206instance Show NP where207show (TermNP d t) = show(d) ++ " " ++ show(t)208show (IntTermNP d t) = show(d) ++ " " ++ show(t)209210data Det = All | Some | No | Most | Atleast | More | Contradiction211deriving (Ord,Eq)212213instance Show Det where214show All = "all"215show Some = "some"216show No = "no"217show Most = "most"218show Atleast = "at least"219show More = "more"220show Contradiction = "contradiction"221222223224data CN = Girls225| Boys226| Dogs | Cats | Skunks | Sneetches | Mammals | Chordates | Animals | Birds | X | Y | Z | W | P | Q | N --Var CNvariable227deriving (Eq,Ord)228229instance Show CN where230show Girls = "girls"231show Boys = "boys"232show Dogs = "dogs"233show Cats = "cats"234show Skunks = "skunks"235show Sneetches = "sneetches"236show Mammals = "mammals"237show Chordates = "chordates"238show Animals = "animals"239show Birds = "birds"240show X = "x"241show Y = "y"242show Z = "z"243show W = "w"244show P = "p"245show Q = "q"246show N = "n"247248data Polarity = Pos | Neg249deriving (Ord, Eq)250251instance Show Polarity where252show Pos = ""253show Neg = "non-"254255data PolCN = PCN Polarity CN256deriving (Eq,Ord)257instance Show PolCN where258show (PCN a b) = (show a)++(show b)259260cnvariables = [X, Y, Z, W, P, Q, N]261262data Term = CNasTerm PolCN263| TermMaker PV NP264| Ter1 | Ter2 | Ter3 | Ter1bar | Ter2bar | Ter3bar265deriving (Ord,Eq)266instance Show Term where267show (CNasTerm px) = show px268show (TermMaker t (TermNP d (TermMaker pv np))) = show(t) ++ " " ++ show(d) ++ " who " ++ show(pv) ++ " " ++ show(np)269show (TermMaker t (TermNP d (CNasTerm px))) = show(t) ++ " " ++ show(d) ++ " " ++ show(px)270--show (TermMaker t n) = "(" ++ show(t) ++ " " ++ show(n)++")" -- this was it!!!271show Ter1 = "Ter1"272show Ter2 = "Ter2"273show Ter3 = "Ter3"274show Ter1bar = "Ter1-bar"275show Ter2bar = "Ter2-bar"276show Ter3bar = "Ter3-bar"277278data PV = PV Polarity V279deriving (Eq,Ord)280instance Show PV where281show (PV a b) = (show a)++(show b)282283data V = Loves | Admires | Helps | Sees | Hates | R | S284deriving (Eq,Ord)285286instance Show V where287show Loves = "love"288show Admires = "admire"289show Helps = "help"290show Sees = "see"291show Hates = "hate"292show R = "r"293show S = "s"294295r = PV Pos R296x = PCN Pos X297y = PCN Pos Y298z = PCN Pos Z299p = PCN Pos P300q = PCN Pos Q301n = PCN Pos N302w = PCN Pos W303non_x = PCN Neg X304non_y = PCN Neg Y305non_z = PCN Neg Z306non_w = PCN Neg W307non_p = PCN Neg P308non_q = PCN Neg Q309non_n = PCN Neg N310skunks = PCN Pos Skunks311mammals = PCN Pos Mammals312animals = PCN Pos Animals313sneetches = PCN Pos Sneetches314dogs = PCN Pos Dogs315birds = PCN Pos Birds316chordates = PCN Pos Chordates317boys = PCN Pos Boys318girls = PCN Pos Girls319cats = PCN Pos Cats320non_skunks = PCN Neg Skunks321non_mammals = PCN Neg Mammals322non_animals = PCN Neg Animals323non_sneetches = PCN Neg Sneetches324non_dogs = PCN Neg Dogs325non_birds = PCN Neg Birds326non_chordates = PCN Neg Chordates327non_boys = PCN Neg Boys328non_girls = PCN Neg Girls329non_cats = PCN Neg Cats330loves = PV Pos Loves331admires = PV Pos Admires332helps = PV Pos Helps333sees = PV Pos Sees334hates = PV Pos Hates335not_loves = PV Neg Loves336not_admires = PV Neg Admires337not_helps = PV Neg Helps338not_sees = PV Neg Sees339not_hates = PV Neg Hates340341342data IntersectionTerm = IntersectionTerm PolCN Term343| IntTer1 | IntTer2 | IntTer3 | IntTer1bar | IntTer2bar | IntTer3bar344deriving (Ord,Eq)345instance Show IntersectionTerm where346show (IntersectionTerm p t) = show(p) ++ " who " ++ show(t)347show IntTer1 = "IntTer1"348show IntTer2 = "IntTer2"349show IntTer3 = "IntTer3"350show IntTer1bar = "IntTer1-bar"351show IntTer2bar = "IntTer2-bar"352show IntTer3bar = "IntTer3-bar"353354355356-------------THIS WHOLE FILE SHOULD BE REWORKED IN THE LIGHT OF THE FRONT END! ------------------357358359360cnlist = [Girls,Boys, Dogs, Cats, Skunks, Mammals, Animals, Chordates, Birds, X, Y, Z, P, Q]361verbList = [Loves, Admires,Helps, Hates,Sees, R, S]362tvVarList = [R,S]363verblistNotVars = verbList \\ tvVarList364cnVarList = [X, Y, Z, P, Q]365cnlistNotVars sList = cnlist \\ cnVarList366polarizedCNListNotVars aList = [CNasTerm (PCN Pos w) | w <- cnlistNotVars aList] ++ [CNasTerm (PCN Neg w) | w <- cnlistNotVars aList]367polarizedTermListNotVars aList = [CNasTerm (PCN Pos w) | w <- cnlistNotVars aList] ++ [CNasTerm (PCN Neg w) | w <- cnlistNotVars aList]368pairOfCns (Sent d (CNasTerm (PCN Pos n1)) (CNasTerm (PCN Pos n2))) = (n1,n2)369370371372s2 = Sent All (CNasTerm x) (CNasTerm y)373t1 = TermMaker sees (TermNP All (CNasTerm skunks) )374t2 = TermMaker sees (TermNP All (CNasTerm girls))375s = Sent All t3 t2376t3 = TermMaker sees (TermNP All t1)377t4 =TermMaker (PV Pos R) (TermNP All (CNasTerm x))378t9 = TermMaker sees (TermNP All (CNasTerm sneetches))379t6 = TermMaker (PV Pos R) (TermNP Some t4)380s3 = Sent All t1 t5381t5 = (CNasTerm animals)382t7 = (CNasTerm chordates)383t8 = TermMaker helps (TermNP All (CNasTerm skunks ))384t10 = (CNasTerm sneetches)385sAllXY = s2386sAllYZ = Sent All (CNasTerm y) (CNasTerm z)387sAllYX = Sent All (CNasTerm y) (CNasTerm x)388sAllXZ = Sent All (CNasTerm x) (CNasTerm z)389sAllXX = Sent All (CNasTerm x) (CNasTerm x)390sAntiXY = Sent All (CNasTerm non_x) (CNasTerm non_y)391sAntiYX = Sent All (CNasTerm non_y) (CNasTerm non_x)392sSomeXX = Sent Some (CNasTerm x) (CNasTerm x)393sSomeXY = Sent Some (CNasTerm x) (CNasTerm y)394sSomeYX = Sent Some (CNasTerm y) (CNasTerm x)395sSomeXZ = Sent Some (CNasTerm x) (CNasTerm z)396sZeroX = Sent All (CNasTerm x) (CNasTerm non_x)397sOneX = Sent All (CNasTerm non_x) (CNasTerm x)398sSome = Sent Some (CNasTerm y) (CNasTerm z)399s4 = Sent Some (CNasTerm dogs) (TermMaker sees (TermNP Some (CNasTerm skunks) ))400s6 = Sent Some (CNasTerm dogs) (TermMaker sees (TermNP Some (CNasTerm skunks) ))401s5 = Sent Some (CNasTerm sneetches) t2402s7 = Sent All t5 t9403s8 = Sent All (CNasTerm dogs) t9404s9 = Sent All t5 t7405s10 = Sent Some t10 t5406s11 = Sent Some (CNasTerm dogs) (TermMaker sees (TermNP Some (CNasTerm sneetches)))407s12 = Sent No t10 t10408sentList = [409(Sent All (CNasTerm skunks) (CNasTerm mammals)),410(Sent Some (CNasTerm skunks) (CNasTerm mammals)),411(Sent All (CNasTerm mammals) (CNasTerm chordates)),412s3, s4, s5, s6, s7, s8, s9, s10, s11, s12413]414415416anotherList =417[ (Sent Some (CNasTerm skunks) (CNasTerm mammals)), (Sent Some (CNasTerm non_chordates) (CNasTerm mammals)),418(Sent All (CNasTerm non_chordates) (CNasTerm dogs)),419(Sent Some (CNasTerm skunks) (CNasTerm boys)), (Sent All (CNasTerm girls) (CNasTerm non_mammals))]420421fourseven = [(Sent All (CNasTerm non_y) (CNasTerm p)), (Sent All (CNasTerm p) (CNasTerm q)),422(Sent All (CNasTerm q) (CNasTerm y)), (Sent All (CNasTerm y) (CNasTerm p)), (Sent All (CNasTerm q) (CNasTerm z))423]424425smallSentList = [(Sent All (CNasTerm skunks) (CNasTerm mammals)),426(Sent Some (CNasTerm skunks) (CNasTerm mammals)),427(Sent Some (CNasTerm non_skunks) (CNasTerm mammals)),428(Sent All (CNasTerm mammals) (CNasTerm non_chordates)), (Sent Some (CNasTerm boys) (CNasTerm non_chordates)),429(Sent All (CNasTerm girls) (CNasTerm non_girls))]430conc = (Sent All t13 t14)431432tinySentList = [(Sent All (CNasTerm skunks) (CNasTerm mammals)),433(Sent Some (CNasTerm mammals) (CNasTerm skunks) ),434(Sent All (CNasTerm sneetches) (CNasTerm skunks))]435436437t11 = TermMaker sees (TermNP All (CNasTerm skunks) )438t12 = TermMaker sees (TermNP All (CNasTerm mammals))439t13 = TermMaker helps (TermNP All t11)440t14 = TermMaker helps (TermNP All t12)441442443444445446447448449type Parser a b = [a] -> [(b,[a])]450type PARSER a b = Parser a (ParseTree a b)451452epsilonT :: PARSER a b453epsilonT = succeed Ep454455symbolT :: Eq a => a -> PARSER a b456symbolT s = (\ x -> Leaf x) <$$> symbol s457458symbol :: Eq a => a -> Parser a a459symbol c [] = []460symbol c (x:xs) | c == x = [(x,xs)]461| otherwise = []462463infixl 6 <:>464465(<:>) :: Parser a b -> Parser a [b] -> Parser a [b]466(p <:> q) xs = [ (r:rs,zs) | (r,ys) <- p xs,467(rs,zs) <- q ys ]468469(<|>) :: Parser a b -> Parser a b -> Parser a b470(p1 <|> p2) xs = p1 xs ++ p2 xs471472(<**>) :: Parser a [b] -> Parser a [b] -> Parser a [b]473(p <**> q) xs = [ (r1 ++ r2,zs) | (r1,ys) <- p xs,474(r2,zs) <- q ys ]475infixl 7 <$$>476477(<$$>) :: (a -> b) -> Parser s a -> Parser s b478(f <$$> p) xs = [ (f x,ys) | (x,ys) <- p xs ]479480data ParseTree a b = Ep | Leaf a | Branch b [ParseTree a b]481deriving Eq482483instance (Show a, Show b) => Show (ParseTree a b) where484show Ep = "[]"485show (Leaf t) = show t486show (Branch l ts) = "[." ++ show l ++ " "487++ show ts ++ "]"488succeed :: b -> Parser a b489succeed r xs = [(r,xs)]490491492collect :: [Parser a b] -> Parser a [b]493collect [] = succeed []494collect (p:ps) = p <:> collect ps495496parseAs :: b -> [PARSER a b] -> PARSER a b497parseAs label ps = (\ xs -> Branch label xs) <$$> collect ps498499sent, tv, cn, det, t, int, intOrT, neg, np :: PARSER String String500cn = symbolT "skunks"501<|> symbolT "mammals"502<|> symbolT "chordates"503<|> symbolT "boys" <|> symbolT "girls" <|> symbolT "animals"504505tv = symbolT "see" <|> symbolT "love" <|> symbolT "admire" <|> symbolT "hate"506507det = symbolT "every"508<|> symbolT "some"509<|> symbolT "no"510<|> symbolT "all"511<|> symbolT "most"512513t = parseAs "Term" [cn]514<|> parseAs "Term" [symbolT "non" ,cn]515<|> parseAs "Term" [tv, det, intOrT]516<|> parseAs "Term" [tv, det, symbolT "who", intOrT]517518--pcn = parseAs "PCN" [pol, cn]519neg = symbolT "non"520521np = parseAs "NP" [det,intOrT]522--pv = parseAs "PV" [pol, tv]523524sent = parseAs "S" [det,intOrT,intOrT]525526int = parseAs "Int" [cn,symbolT "who",t]527528intOrT = int <|> t529530move :: ParseTree String String -> Term531move (Branch "Term" [Leaf "skunks"]) = (CNasTerm skunks)532move (Branch "Term" [Leaf "mammals"]) = (CNasTerm mammals)533move (Branch "Term" [Leaf "animals"]) = (CNasTerm animals)534move (Branch "Term" [Leaf "chordates"]) = (CNasTerm chordates)535move (Branch "Term" [Leaf "sneetches"]) = (CNasTerm sneetches)536move (Branch "Term" [(Leaf "non"), (Leaf "skunks")]) = (CNasTerm non_skunks)537move (Branch "Term" [(Leaf "non"), Leaf "mammals"]) = (CNasTerm non_mammals)538move (Branch "Term" [(Leaf "non"), Leaf "animals"]) = (CNasTerm non_animals)539move (Branch "Term" [(Leaf "non"), Leaf "chordates"]) = (CNasTerm non_chordates)540move (Branch "Term" [(Leaf "non"), Leaf "sneetches"]) = (CNasTerm non_sneetches)541542543move (Branch "Term" [(Leaf "see"), (Leaf "all"), (Leaf "who"), subtree])544= (TermMaker sees (TermNP All (move subtree)))545move (Branch "Term" [(Leaf "see"), (Leaf "all"), subtree])546= (TermMaker sees (TermNP All (move subtree)))547move (Branch "Term" [(Leaf "love"), (Leaf "all"), (Leaf "who"), subtree])548= (TermMaker loves (TermNP All (move subtree)))549move (Branch "Term" [(Leaf "love"), (Leaf "all"), subtree])550= (TermMaker loves (TermNP All (move subtree)))551move (Branch "Term" [(Leaf "hate"), (Leaf "all"), (Leaf "who"), subtree])552= (TermMaker hates (TermNP All (move subtree)))553move (Branch "Term" [(Leaf "hate"), (Leaf "all"), subtree])554= (TermMaker hates (TermNP All (move subtree)))555move (Leaf "skunks") = (CNasTerm skunks)556--move (Leaf ["mammals"]) = (CNasTerm mammals)557--move (Leaf ["animals"]) = (CNasTerm animals)558559moveS :: ParseTree String String -> Sent560moveS (Branch "S" [(Leaf "all"), ttree, ttree2]) = (Sent All (move ttree) (move ttree2))561562readMe = moveS . fst . head . sent . words563564sentParses :: String -> [Sent]565sentParses =566map (moveS . fst)567. filter (null . snd)568. sent569. words570571-----USAGE: moveS $ (fst.head) $ sent $ words "all see all see all skunks love all mammals"572---- ALSO move $ (fst . head) $ t $ words "see all see all non skunks"573--- note how 'non' worls574575split2 :: [t] -> [[[t]]] ---- split2 takes any list $\ell$ and gives the list of all ways to split $\ell$ into two sublists576--- whose concatenation is $\ell$ again.577split2 [] = [[[],[]]]578split2 (x:xs) = [[ [], x:xs]] ++ map (\z -> [x:(z!!0),z!!1]) (split2 xs)579580split2' :: [t] -> [([t],[t])]581split2' = \case582xs@(x : xs') -> ([],xs) : map (first (x :)) (split2' xs')583584{-585[] = [([],[])]586split2' (x:xs) = [[ [], x:xs]] ++ map (\z -> [x:(z!!0),z!!1]) (split2 xs)587-}588589tF :: [String] -> [Term]590tF quoted -- this parses terms591| quoted == [] = []592| (quoted!! 0 == "who") = tF $ drop 1 quoted593| (quoted!! 0 == "are") = tF $ drop 1 quoted594| quoted == ["skunks"] = [CNasTerm skunks]595| quoted == ["mammals"] = [CNasTerm mammals]596| quoted == ["chordates"] = [CNasTerm chordates]597| quoted == ["boys"] = [CNasTerm boys]598| quoted == ["girls"] = [CNasTerm girls]599| quoted == ["dogs"] = [CNasTerm dogs]600| quoted == ["cats"] = [CNasTerm cats]601| quoted == ["birds"] = [CNasTerm birds]602| quoted == ["animals"] = [CNasTerm animals]603| quoted == ["sneetches"] = [CNasTerm sneetches]604| quoted == ["non-skunks"] = [CNasTerm non_skunks]605| quoted == ["non-mammals"] = [CNasTerm non_mammals]606| quoted == ["non-chordates"] = [CNasTerm non_chordates]607| quoted == ["non-boys"] = [CNasTerm non_boys]608| quoted == ["non-girls"] = [CNasTerm non_girls]609| quoted == ["non-dogs"] = [CNasTerm non_dogs]610| quoted == ["non-cats"] = [CNasTerm non_cats]611| quoted == ["non-birds"] = [CNasTerm non_birds]612| quoted == ["non-animals"] = [CNasTerm non_animals]613| quoted == ["non-sneetches"] = [CNasTerm non_sneetches]614| quoted == ["x"] = [CNasTerm x]615| quoted == ["y"] = [CNasTerm y]616| quoted == ["z"] = [CNasTerm z]617| quoted == ["p"] = [CNasTerm p]618| quoted == ["q"] = [CNasTerm q]619| quoted == ["non-x"] = [CNasTerm non_x]620| quoted == ["non-y"] = [CNasTerm non_y]621| quoted == ["non-z"] = [CNasTerm non_z]622| quoted == ["non-p"] = [CNasTerm non_p]623| quoted == ["non-q"] = [CNasTerm non_q]624| (quoted!! 0 == "see") = [(TermMaker sees r) | r <- (npF (drop 1 quoted))]625| (quoted!! 0 == "sees") = [(TermMaker sees r) | r <- (npF (drop 1 quoted))]626| (quoted!! 0 == "admires") = [(TermMaker admires r) | r <- (npF (drop 1 quoted))]627| (quoted!! 0 == "admire") = [(TermMaker admires r) | r <- (npF (drop 1 quoted))]628| (quoted!! 0 == "loves") = [(TermMaker loves r) | r <- (npF (drop 1 quoted))]629| (quoted!! 0 == "love") = [(TermMaker loves r) | r <- (npF (drop 1 quoted))]630| (quoted!! 0 == "helps") = [(TermMaker helps r) | r <- (npF (drop 1 quoted))]631| (quoted!! 0 == "help") = [(TermMaker helps r) | r <- (npF (drop 1 quoted))]632| (quoted!! 0 == "hates") = [(TermMaker hates r) | r <- (npF (drop 1 quoted))]633| (quoted!! 0 == "hate") = [(TermMaker hates r) | r <- (npF (drop 1 quoted))]634| (quoted!! 0 == "doesn't-see") = [(TermMaker not_sees r) | r <- (npF (drop 1 quoted))]635| (quoted!! 0 == "doesn't-admire") = [(TermMaker not_admires r) | r <- (npF (drop 1 quoted))]636| (quoted!! 0 == "doesn't-love") = [(TermMaker not_loves r) | r <- (npF (drop 1 quoted))]637| (quoted!! 0 == "doesn't-help") = [(TermMaker not_helps r) | r <- (npF (drop 1 quoted))]638| (quoted!! 0 == "doesn't-hate") = [(TermMaker not_hates r) | r <- (npF (drop 1 quoted))]639| (quoted!! 0 == "don't-see") = [(TermMaker not_sees r) | r <- (npF (drop 1 quoted))]640| (quoted!! 0 == "don't-admire") = [(TermMaker not_admires r) | r <- (npF (drop 1 quoted))]641| (quoted!! 0 == "don't-love") = [(TermMaker not_loves r) | r <- (npF (drop 1 quoted))]642| (quoted!! 0 == "don't-help") = [(TermMaker not_helps r) | r <- (npF (drop 1 quoted))]643| (quoted!! 0 == "don't-hate") = [(TermMaker not_hates r) | r <- (npF (drop 1 quoted))]644| (quoted!! 0 == "r") = [(TermMaker r blurt) | blurt <- (npF (drop 1 quoted))]645| otherwise = []646647{--648intTF quoted649| (quoted !! 0 == ["skunks"]) = [(IntersectionTerm (PCN Pos Skunks) x) | x <- (map tF (drop 1 quoted))]650| quoted !! 0 == ["mammals"] = [CNasTerm mammals]651| quoted !! 0== ["chordates"] = [CNasTerm chordates]652| quoted !! 0== ["boys"] = [CNasTerm boys]653| quoted !! 0 == ["girls"] = [CNasTerm girls]654| quoted !! 0 == ["dogs"] = [CNasTerm dogs]655| quoted !! 0 == ["cats"] = [CNasTerm cats]656| quoted !! 0 == ["birds"] = [CNasTerm birds]657| quoted !! 0 == ["animals"] = [CNasTerm animals]658| quoted !! 0 == ["sneetches"] = [CNasTerm sneetches]659| otherwise = []660--}661662npF x --- this parses noun phrases663| x == [] = []664| (x!! 0 == "all") = [(TermNP All w) | w <- tF (drop 1 x)]665| (x!! 0 == "some") = [(TermNP Some w) | w <- tF (drop 1 x)]666| (x!! 0 == "no") = [(TermNP No w) | w <- tF (drop 1 x)]667| (x!! 0 == "most") = [(TermNP Most w) | w <- tF (drop 1 x)]668| otherwise = []669670readS input = --- this parses sentences671let672w = words input673firstWord = head w674y = tail w675sp = split2 y676tr = [ x | x <- (map (map tF) sp), (x!!0) /= [], (x!!1) /= []]677a = head $ head $ head tr678b = head $ head $ tail $ head tr679output680| firstWord == "all" = Sent All a b681| firstWord == "some" = Sent Some a b682| firstWord == "most" = Sent Most a b683| firstWord == "atleast" = Sent Atleast a b684| firstWord == "more" = Sent More a b685| firstWord == "no" = Sent No a b686| firstWord == "All" = Sent All a b687| firstWord == "Some" = Sent Some a b688| firstWord == "Most" = Sent Most a b689| firstWord == "No" = Sent No a b690in output691692readSs = map readS693694toMaybe :: Foldable t => t a -> Maybe a695toMaybe = foldl (maybe Just (const . Just)) Nothing696697698readS' :: String -> Maybe Sent699readS' input = case words input of700w0:ws -> do701q <- lookup (toLower <$> w0)702[ ( "all" , All )703, ( "some" , Some )704, ( "most" , Most )705, ( "atleast" , Atleast )706, ( "more" , More )707, ( "no" , No )708]709(a,b) <- listToMaybe710$ split2' ws >>= uncurry zip . (tF *** tF)711return $ Sent q a b712_ -> Nothing713714-- return either the strings which failed to be parsed,715-- or the full set of parsed sentences.716readSs' :: [String] -> Either [String] [Sent]717readSs' = foldr rS $ Right []718where719rS :: String -> Either [String] [Sent] -> Either [String] [Sent]720rS s es = case readS' s of721Just s' -> case es of722Left bad -> Left bad723Right good -> Right $ s' : good724Nothing -> case es of725Left bad -> Left $ s : bad726Right good -> Left [s]727728729type RuleName = String730data Rule = Rule {rulename :: RuleName,731premises :: [Sent],732conclusion :: Sent}733deriving (Show, Eq)734type RuleList = [Rule]735736junk = Rule {rulename = "junk", premises = readSs ["all x x", "all y y"] , conclusion = readS "all x y"}737738anti = Rule {rulename = "anti", premises = readSs ["all x y"] , conclusion = readS "all non-y non-x"}739barbara = Rule {rulename = "barbara", premises = readSs ["all x y", "all y z"] , conclusion = readS "all x z"}740some1 = Rule {rulename = "some1", premises = readSs ["some x y"], conclusion = readS "some x x"}741some2 = Rule {rulename = "some2", premises = readSs ["some x y"], conclusion = readS "some y x"}742darii = Rule {rulename = "darii", premises = readSs ["all y z", "some x y"], conclusion = readS "some x z"}743zero = Rule {rulename = "zero", premises = readSs ["all x non-x"], conclusion =readS "all x y"}744one = Rule {rulename = "one", premises = readSs ["all non-x x"], conclusion =readS "all y x"}745axiom = Rule {rulename = "axiom", premises = [], conclusion =readS "all x x"}746exFalso = Rule {rulename = "X", premises = readSs ["some x y", "all x non-y"],747conclusion = Sent Contradiction (CNasTerm x) (CNasTerm y) }748sdagger = [anti,barbara,some1, some2, darii,zero,axiom,exFalso]749750antiARC = Rule {rulename = "anti", premises = [Sent All Ter1 Ter2], conclusion = (Sent All (TermMaker r (TermNP All Ter2)) (TermMaker r (TermNP All Ter1)))}751barbaraARC = Rule {rulename = "barbara", premises = [Sent All Ter1 Ter2, Sent All Ter2 Ter3], conclusion =(Sent All Ter1 Ter3)}752allARC = Rule {rulename = "down", premises = [Sent All Ter1 Ter2, Sent All Ter3 (TermMaker r (TermNP All Ter2)) ], conclusion = (Sent All Ter3 (TermMaker r (TermNP All Ter1)))}753754755756757758data PTree a = T a [PTree a]759deriving (Show, Eq)760761lineNumberHelp :: [(a, [Int], Int)] -> [(a, [Int], Int)] -> [(a, [Int], Int)]762lineNumberHelp firstseq secondseq =763let764n = if null firstseq then 0 else (get3 $ head firstseq)765modify w = map ( \ (x, listofInts, k) -> (x, (map (\ i -> 1 + n+i) listofInts), k)) w766in (firstseq ++ modify secondseq)767768------ near of a PTree lists the nodes in depth-first order, along with an extra list for each node.769------ for the node n in the tree it lists the addresses of the children of n in the same tree, again in the770------ depth-first order of the tree overall. Getting this right was probably the hardest part of this whole exercise.771------ Note also that what we want in the end is not the depth-first listing of the PTree but rather the 'bottom-up' listing,772------ and these are related by773------774------ bottom_up t = reverse (depth_first ( tree_reverse t))775776near :: (PTree a) -> [(a, [Int], Int)]777near (T x l) = [(x,s, k+1 )] ++ extrastuff778where779k = sum r780--extrastuff :: [(a, [Int], Int)]781extrastuff = foldl lineNumberHelp [] (map near l)782--q :: [(a, [Int], Int)]783q = map head $ map near l784r :: [Int]785r = map get3 q786s = init( scanl (+) 2 r)787788tree_reverse (T n t) = T n (map tree_reverse (reverse t))789790full_reverse :: [(a, [Int], Int)] -> [(Int, a, [Int])]791full_reverse h =792let793n = length h794p = [(i, reverse( map (\ x -> n + 1 - x) j )) | (i,j,k) <- h]795q = reverse p796w = [1..n]797mergeMe :: [Int] -> [(a,[Int])] -> [(Int,a,[Int])]798mergeMe [] [] = []799mergeMe (i:wMore) (pair:pMore) = (i, (fst pair), (snd pair)) : (mergeMe wMore pMore)800in mergeMe w q801802803804805dropList :: [Int] -> Int -> [Int]806dropList list x = [i | i <- list, i /= x]807dropM :: M -> Int -> M808dropM m x = M { noun = (noun m), items = (dropList (items m) x) }809dropVb :: Vb -> Int -> Vb810dropVb v x = Vb { verb = (verb v), verb_items = [(i,j) | (i,j) <- verb_items v, i/= x, j/= x]}811dropModel :: Model -> Int -> Model812dropModel m x = Model { universe = (dropList (universe m) x), cnDict = map (\ n -> (dropM n x)) (cnDict m) , verbDict = map (\ v -> (dropVb v x)) (verbDict m) }813814consecutiveDropList :: [Int] -> Int -> [Int]815helpForConsecutiveDrop :: Int -> Int -> Int816helpForConsecutiveDrop k l = if k < l then k else k -1817consecutiveDropList list x = [helpForConsecutiveDrop i x | i <- list, i /= x]818consecutiveDropM m x = M { noun = (noun m), items = (consecutiveDropList (items m) x) }819consecutiveDropVb :: Vb -> Int -> Vb820consecutiveDropVb v x = Vb { verb = (verb v), verb_items = [(helpForConsecutiveDrop i x, helpForConsecutiveDrop j x) | (i,j) <- verb_items v, i/= x, j/= x]}821consecutiveDropModel :: Model -> Int -> Model822consecutiveDropModel m x = Model { universe = (consecutiveDropList (universe m) x), cnDict = map (\ n -> (consecutiveDropM n x)) (cnDict m) , verbDict = map (\ v -> (consecutiveDropVb v x)) (verbDict m) }823824maybeDrop model x gamma =825let826mNew = consecutiveDropModel model x --- was dropModel, not consecutiveDropModel827tvs = map (\ s -> (semanticsSent s mNew)) gamma828in829if (and tvs) then mNew else model830831shorten :: Model -> [Sent] -> Model832shorten model gamma = foldl (\ m -> (\ x -> maybeDrop m x gamma)) model (universe model)833834iterativelyShorten model gamma = if (model == shorten model gamma) then model else (iterativelyShorten (shorten model gamma) gamma)835836{--dropALot m gamma = foldl (\acc x -> listU m) (listU m)837--}838data SentencesInModel = SentencesInModel { sentFromModels :: String, truthvalueOfSent :: [Bool]}839deriving Show840841data M = M { noun :: CN, items :: [Int] }842deriving (Eq, Show)843844data Vb = Vb { verb :: V, verb_items :: [(Int,Int)] }845deriving (Eq,Show)846847type Universe = [Int]848data Model = Model {universe::Universe, cnDict :: [M], verbDict :: [Vb]}849deriving (Eq,Show)850851semanticsTerm :: Term -> Model -> [Int]852semanticsTerm (CNasTerm (PCN Pos cn)) m = helper (CNasTerm (PCN Pos cn)) (cnDict m)853semanticsTerm (CNasTerm (PCN Neg cn)) m = (universe m) \\ semanticsTerm (CNasTerm (PCN Pos cn)) m854semanticsTerm (TermMaker (PV Pos tv) (TermNP All t)) m =855let856u = universe m857tt = semanticsTerm t m858vv = verbHelper tv (verbDict m)859in860[ x | x <- u, and (map (\ y -> implies (y `elem` tt) ((x,y) `elem` vv)) u)]861862semanticsTerm (TermMaker (PV Pos tv) (TermNP Some t)) m =863let864u = universe m865tt = semanticsTerm t m866vv = verbHelper tv (verbDict m)867in868[ x | x <- u, or (map (\ y -> (y `elem` tt) && ((x,y) `elem` vv)) u)]869870semanticsTerm (TermMaker (PV Neg tv) (TermNP All t)) m =871let872u = universe m873tt = semanticsTerm t m874vv = verbHelper tv (verbDict m)875in876[ x | x <- u, and (map (\ y -> implies (y `elem` tt) (not ((x,y) `elem` vv)) ) u)]877878semanticsTerm (TermMaker (PV Neg tv) (TermNP Some t)) m =879let880u = universe m881tt = semanticsTerm t m882vv = verbHelper tv (verbDict m)883in884[ x | x <- u, or (map (\ y -> (y `elem` tt) && (not ((x,y) `elem` vv)) ) u)]885886helper (CNasTerm (PCN Pos cn)) partialList887| null partialList = []888| cn == (noun $ head $ partialList) = items $ head partialList889| otherwise = helper (CNasTerm (PCN Pos cn)) (tail partialList)890891implies b c = (not b) || c892893verbHelper v vList894| null vList = []895| v == (verb $ head $ vList) = verb_items $ head vList896| otherwise = verbHelper v (tail vList)897898semanticsSent :: Sent -> Model -> Bool899semanticsSent (Sent All t1 t2) m = and ( map (\ x -> x `elem` s2) s1)900where901s1 = semanticsTerm t1 m902s2 = semanticsTerm t2 m903904semanticsSent (Sent Some t1 t2) m = or (map (\ x -> x `elem` s2) s1)905where906s1 = semanticsTerm t1 m907s2 = semanticsTerm t2 m908909semanticsSent (Sent No t1 t2) m = and ( map (\ x -> not (x `elem` s2)) s1)910where911s1 = semanticsTerm t1 m912s2 = semanticsTerm t2 m913914semanticsSent (Sent Most t1 t2) m =915let916s1 = semanticsTerm t1 m917s2 = semanticsTerm t2 m918intersection = s1 `intersect` s2919n = length s1920k = length intersection921in922n < 2 * k923924semanticsSent (Sent Atleast t1 t2) m =925let926s1 = semanticsTerm t1 m927s2 = semanticsTerm t2 m928in929s2 <= s1930931semanticsSent (Sent More t1 t2) m =932let933s1 = semanticsTerm t1 m934s2 = semanticsTerm t2 m935in936s2 < s1937938--------- pretty printing of models below939940data U = U {name::String, itemsU :: [Int] }941deriving Show942943transMtoU t = (U (show(noun t)) (items t))944945data Vextra = Vextra { verbextra :: String, verb_items_extra :: [(Int,Int)] }946deriving Show947948transVtoVextra t = (Vextra (show(verb t)) (verb_items t))949950-- a type for fill functions951type Filler = Int -> String -> String952953-- a type for describing table columns954data ColDesc t = ColDesc955{ colTitleFill :: Filler956, colTitle :: String957, colValueFill :: Filler958, colValue :: t -> String959}960961-- test data962test =963[ M Cats [1,2,3],964M Dogs [4,5,6],965M Skunks [1,3,5,6],966M Chordates [ ]967]968969vTest = [Vb Sees [(1,1),(1,4),(3,4),(2,5)]]970971model1 = Model {universe = [1,2,3,4,5,6], cnDict = test, verbDict = vTest}972973-- functions that fill a string (s) to a given width (n) by adding pad974-- character (c) to align left, right, or center975fillLeft c n s = s ++ replicate (n - length s) c976fillRight c n s = replicate (n - length s) c ++ s977fillCenter c n s = replicate l c ++ s ++ replicate r c978where x = n - length s979l = x `div` 2980r = x - l981982-- functions that fill with spaces983newleft = fillLeft ' '984right = fillRight ' '985center = fillCenter ' '986--showTable :: [ColDesc t] -> [t] -> String987988989showTable cs ts =990let header = map colTitle cs991rows = [[colValue c t | c <- cs] | t <- ts]992widths = [maximum $ map length col | col <- transpose $ header : rows]993separator = intercalate "-+-" [replicate width '-' | width <- widths]994fillCols fill cols = intercalate " | " [fill c width col | (c, width, col) <- zip3 cs widths cols]995in996unlines $ fillCols colTitleFill header : separator : map (fillCols colValueFill) rows997998showModelNounsPlusJustifications m gamma phi = do999putStrLn ("The universe is the set of numbers in " ++ show(universe m)++".")1000putStrLn " "1001putStrLn "The nouns are interpreted as follows:"1002putStrLn " "1003showNouns m1004putStrLn " "1005putStrLn "Here is how the assumptions and purported conclusion fare in this model:"1006putStrLn " "1007showSentenceTruthValues m $ gamma++[phi]10081009showModelNounsVerbsPlusJustifications m gamma phi = do1010putStrLn ("The universe is the set of numbers in " ++ show(universe m)++".")1011putStrLn " "1012putStrLn "The nouns and verbs are interpreted as follows:"1013putStrLn " "1014showNouns m1015putStrLn " "1016showVerbs m1017putStrLn "Here is how the assumptions and purported conclusion fare in this model:"1018putStrLn " "1019showSentenceTruthValues m $ gamma++[phi]10201021showModelNounsOnly m = do1022putStrLn ("The universe is the set of numbers in " ++ show(universe m)++".")1023putStrLn " "1024putStrLn "The nouns are interpreted as follows:"1025putStrLn " "1026showNouns m10271028showModel m = do1029putStrLn ("The universe is the set of numbers in " ++ show(universe m)++".")1030putStrLn " "1031putStrLn "The nouns are interpreted as follows:"1032putStrLn " "1033showNouns m1034putStrLn "The transitive verbs are interpreted as follows:"1035putStrLn " "1036showVerbs m10371038showNouns m = putStrLn $1039showTable1040[ ColDesc center "Noun" newleft name1041, ColDesc center "Interpretation" newleft (intercalate ", " . map show . itemsU)1042]1043$ map transMtoU (cnDict m)10441045showVerbs m = putStrLn $1046showTable1047[ ColDesc center "Verb" newleft verbextra1048, ColDesc center "Interpretation" newleft (intercalate ", " . map show . verb_items_extra)1049]1050$ map transVtoVextra (verbDict m)10511052--- showGeneric below is used in showModelPlus1053showGeneric m nameLabel contentLabel recordList = putStrLn $1054showTable1055[ ColDesc center "Term" newleft nameLabel1056, ColDesc center "Interpretation" newleft (intercalate ", " . map show . contentLabel)1057] recordList10581059makeSentenceEntry s m = SentencesInModel (show s) [semanticsSent s m]10601061showSentenceTruthValues m gamma = putStrLn $1062showTable1063[ ColDesc center "Sentence" newleft sentFromModels1064, ColDesc center "Truth Value" newleft (intercalate ", " . map show . truthvalueOfSent )1065] (map (\ x -> makeSentenceEntry x m) (gamma))10661067showModelPlus mod tList = do1068showModel mod1069putStrLn " "1070putStrLn "Extra information on the relevant terms:"1071putStrLn " "1072let rrrList = map (\ z -> (U { name = (show z) , itemsU = (semanticsTerm z mod) }) ) tList1073showGeneric mod name itemsU rrrList10741075showModelNounsVerbsPlusJustificationsARC :: Model -> [Sent] -> Sent -> [Term] -> IO ()1076showModelNounsVerbsPlusJustificationsARC m gamma phi tList = do1077putStrLn ("The universe is the set of numbers in " ++ show(universe m)++".")1078putStrLn " "1079putStrLn "The nouns and verbs are interpreted as follows:"1080putStrLn " "1081showNouns m1082putStrLn " "1083showVerbs m1084putStrLn "Extra information on the relevant terms:"1085putStrLn " "1086let rrrList = map (\ z -> (U { name = (show z) , itemsU = (semanticsTerm z m) }) ) tList1087showGeneric m name itemsU rrrList1088putStrLn "Here is how the assumptions and purported conclusion fare in this model:"1089putStrLn " "1090showSentenceTruthValues m (gamma++[phi])10911092{-1093m gamma phi tList1094-----------------1095show (universe m)1096showNouns n:1097showTable1098[ ColDesc center "Noun" newleft name1099, ColDesc center "Interpretation" newleft (intercalate ", " . map show . itemsU)1100]1101$ map transMtoU (cnDict m)1102showVerbs m:1103showTable1104[ ColDesc center "Verb" newleft verbextra1105, ColDesc center "Interpretation" newleft (intercalate ", " . map show . verb_items_extra)1106]1107$ map transVtoVextra (verbDict m)1108showGeneric m name itemsU (...):1109showTable1110[ ColDesc center "Term" newleft name1111, ColDesc center "Interpretation" newleft (intercalate ", " . map show . itemsU)1112] $ map (\ z -> U { name = show z, itemsU = semanticsTerm z m }) tList1113showSentenceTruthValues m $ gamma ++ [phi]:1114showTable1115[ ColDesc center "Sentence" newleft sentFromModels1116, ColDesc center "Truth Value" newleft (intercalate ", " . map show . truthvalueOfSent )1117]1118$ map (\ x -> makeSentenceEntry x m) $ gamma ++ [phi]1119-}1120112111221123{-# LANGUAGE PatternGuards #-}112411251126get1 (a,b,c) = a1127get2 (a,b,c) = b1128get3 (a,b,c) = c11291130get1Of4 (a,b,c,d) = a1131get2Of4 (a,b,c,d) = b1132get3Of4(a,b,c,d) = c1133get4Of4(a,b,c,d) = d11341135--firstHelp :: a -> [a] -> [[a]]1136firstHelp x [] = []1137firstHelp x (y:ytail) = (x,y) : firstHelp x ytail11381139--secondHelp :: [a] -> [a] -> [[[a]]]1140secondHelp list ys = map (\ x -> firstHelp x ys) list11411142allFns list1 list2 = sequence $ (secondHelp list1 list2)11431144lookfor key ((a,b):abs)1145| key == a = b11461147emptyAsDefault :: Maybe [a] -> [a]1148emptyAsDefault mx = case mx of1149Nothing -> []1150Just xy -> xy1151zeroAsDefault :: Maybe Int -> Int1152zeroAsDefault mx = case mx of1153Nothing -> 01154Just xy -> xy11551156findD (Sent d t1 t2) = d1157g1 (Sent d t1 t2) = t11158g2 (Sent d t1 t2) = t211591160addAssumptionAsReason :: Sent -> (Sent, String, [Sent])1161addAssumptionAsReason s = (s, "A", [])1162addReasonsToOriginal :: [Sent] -> [(Sent,String,[Sent])]1163addReasonsToOriginal = map addAssumptionAsReason11641165varsInConclusion :: Rule -> [Term]1166varsInConclusion r = nub [g1 $ conclusion r, g2 $ conclusion r]11671168premiseExtractPairs :: Rule -> [(Term,Term)]1169premiseExtractPairs r =1170let f (Sent d t1 t2) = (t1, t2)1171in map f $ premises r11721173varsInPremises :: Rule -> [Term]1174varsInPremises r = concat [[a,b] | (a,b) <- premiseExtractPairs r]117511761177extras :: Rule -> [Term]1178extras r = (varsInConclusion r) \\ (varsInPremises r)11791180-- I am not sure if 'extras' just above is used. But the variants below are used.11811182extracnsInRule r = nub $ (cnsIn (conclusion r) ) \\ (concatMap cnsIn (premises r))1183extraVerbsInRule r = nub $ (verbsIn (conclusion r) ) \\ (concatMap verbsIn (premises r))11841185fixDuplicates xs = nubBy conclusionsMatch xs1186where conclusionsMatch ys zs =1187get1 ys == get1 zs11881189--------------------------- here is where the main part of the code starts11901191buildPairOfSubs :: Sent -> [Sent] -> [(Sent, Maybe [(Term, Term)], Maybe [(PV, PV)])]1192buildPairOfSubs sent sList = [(s, buildTermSub sent s,buildPVSub sent s) | s <- sList, Nothing /= buildTermSub sent s, Nothing /= buildPVSub sent s ]11931194ruleToPairOfSubs :: Rule -> [Sent] -> [[(Sent, Maybe [(Term, Term)], Maybe [(PV, PV)])]]1195ruleToPairOfSubs rule sList = map (\ x -> buildPairOfSubs x sList) (premises rule)11961197applicableInstances :: Rule -> [Sent] -> [([Sent], [(Term, Term)], [(PV, PV)])]1198applicableInstances rule sList =1199let1200jj = sequence $ (ruleToPairOfSubs rule sList)1201checkerUnary x = foldl combineStructures (Just []) (map get2 x)1202checkerBinary x = foldl combineStructures (Just []) (map get3 x)1203in1204[((map get1 x), (emptyAsDefault $ checkerUnary x), (emptyAsDefault $ checkerBinary x)) | x <- jj, Nothing /= checkerUnary x, Nothing /= checkerBinary x]1205120612071208extraReconciliationVerbs rule sList = if extraVerbsInRule rule == [] then (applicableInstances rule sList) else1209let1210above = [[((PV Pos x),(PV Pos y))] | x <- (extraVerbsInRule rule), y<- verblistNotVars]1211in1212concatMap (\ y -> (map (\ x -> (get1 x, get2 x , (get3 x ++ y))) (applicableInstances rule sList ))) above121312141215extraReconciliationCNs rule sList = if extracnsInRule rule == [] then (extraReconciliationVerbs rule sList) else1216let1217useThese = nub $ concatMap cnsIn sList1218firstSet = [CNasTerm (PCN Pos cn1 ) | cn1 <- (extracnsInRule rule)]1219secondSet = [CNasTerm (PCN Pos cn2 ) | cn2 <- useThese]1220firstSetNeg = [CNasTerm (PCN Neg cn1 ) | cn1 <- (extracnsInRule rule)]1221secondSetNeg = [CNasTerm (PCN Neg cn2 ) | cn2 <- useThese]1222tv = or $ map (hasNegativeMarker . pCNsIn) $ concatMap subterms sList1223extras = if tv then allFns firstSet secondSetNeg else [ ]1224subs = (allFns firstSet secondSet) ++ extras1225in1226concatMap (\ y -> (map (\ x -> (get1 x, (get2 x ++ y) , get3 x)) (extraReconciliationVerbs rule sList ))) subs1227122812291230render rule item =1231let t = conclusion rule1232u = spellOut t (get2 item) (get3 item)1233in (u, (rulename rule), get1 item)12341235dropReasons = map get1123612371238applyARule sList r = nub $ map (\ x -> render r x) (extraReconciliationCNs r sList)12391240applyAllRules sListWithReasons rl =1241let1242z = dropReasons sListWithReasons1243a = map (applyARule z) rl1244b = concat a1245in1246fixDuplicates $ sListWithReasons ++ b124712481249type SentRule = (Sent,String)1250--data PTree = T (Sent,String) [PTree] ---- for development purposes, this declaration was moved to ProofTreeNumbers.hs1251-- deriving (Show, Eq)1252125312541255ll phi stumpset =1256if (get1 $ (stumpset !! 0)) == phi then (stumpset !! 0) else (ll phi (tail stumpset))12571258proofSearch phi stumpset =1259T ((get1 a), (get2 a)) (map (\ x -> (proofSearch x stumpset)) (get3 a))1260where a = ll phi stumpset126112621263firstRepeat (x:y:rest) = if x == y then x else firstRepeat (y:rest)12641265allDerived :: [Sent] -> [Rule] -> [(Sent, RuleName, [Sent])]1266allDerived noReasons rl = allDerivedUnderRepresentations noReasons rl126712681269allDerivedUnderRepresentations noReasons rl= firstRepeat $ fixedPoint addReasons rl1270where addReasons = addReasonsToOriginal noReasons12711272fixedPoint withReasons rl = withReasons : map (\ x -> applyAllRules x rl) (fixedPoint withReasons rl)12731274fullStory noReasonList ruleList = fullStoryUnderRepresentations (readSs noReasonList) ruleList1275--- e.g. fullStory ["all skunks mammals", "some mammals non-chordates"] sdagger12761277--fullStoryUnderRepresentations :: AssumptionList -> [Rule] -> IO ()1278fullStoryUnderRepresentations noReasonList ruleList = mapM_ print $ map get1 $ allDerivedUnderRepresentations noReasonList ruleList12791280modify outputList = map (\ x -> (get1 x, fst (get2 x), snd(get2 x), get3 x)) outputList12811282-- let stumpset = allDerived [s8,s12] sList1283-- let phi = get1 $ stumpset !! 131284findProofByNumber n ch = mapM_ print $ modify . full_reverse . near . tree_reverse $ proofSearch (get1 (ch !! n)) ch12851286inconsistency stumpset =1287let1288q = map get1 stumpset1289--qq = map principalDet q1290in1291dropWhile (\ s -> Contradiction /= principalDet s)q12921293-- relevantChunk is NOT USED!12941295relevantChunk phi gamma ruleList =1296let1297addReasons = addReasonsToOriginal gamma1298bingo = fixedPoint addReasons ruleList1299firstRepeatOrFind (x:y:rest)1300| phi `elem` (map get1 x) = x1301| (inconsistency x) /= [] = x1302| x == y = x1303| otherwise = firstRepeatOrFind (y:rest)1304in firstRepeatOrFind bingo130513061307follows phi gamma ruleList = followsUnderRepresentation (readS phi) (readSs gamma) ruleList13081309followsUnderRepresentation phi gamma ruleList =1310let1311addReasons = addReasonsToOriginal gamma1312bingo = fixedPoint addReasons ruleList1313firstRepeatOrFind (x:y:rest)1314| phi `elem` (map get1 x) = do1315putStrLn " "1316putStrLn "The sentence follows, and here is a derivation in the given logic from the assumptions:"1317putStrLn " "1318mapM_ print $ modify . full_reverse $ near $ tree_reverse $ proofSearch phi x1319putStrLn " "1320| (inconsistency x) /= [] = do1321putStrLn " "1322putStrLn "As shown below, the list of assumptions is inconsistent, so every sentence follows."1323putStrLn " "1324mapM_ print $ modify . full_reverse $ near $ tree_reverse $ proofSearch (head $ (inconsistency x)) x1325| x == y = do1326putStrLn " "1327putStrLn "The given sentence is not provable from the assumptions in the logic."1328putStrLn " "1329| otherwise = firstRepeatOrFind (y:rest)1330in firstRepeatOrFind bingo13311332--- :set +s for timing1333133413351336---- EXTRA STUFF TO TRY TO PRETTY-PRINT THE PROOFS IN 3 NICE COLUMNS1337---- SO FAR, NO LUCK!13381339--import Data.List (transpose, intercalate)134013411342-- a type for records1343data K = K { make :: String1344, model :: String1345, modell :: String1346, years :: [Int] }1347deriving Show1348134913501351135213531354data SToPrint = SToPrint { lineToPrint :: Int1355, sentToPrint :: Sent1356, ruleToPrint :: RuleName1357, reasonsToPrint :: [Int] }1358deriving Show13591360136113621363-- functions that fill with spaces13641365type Proof = [(Int,Sent,RuleName,[Int])]1366type ProofChunk = [(Sent,RuleName,[Sent])]1367type StopList = [Term]13681369oneStepARC :: StopList1370-> ProofChunk1371-> ProofChunk1372oneStepARC stopList gammaWithReasons =1373fixDuplicates $ gammaWithReasons ++1374filter (checkARC stopList . get1)1375( concatMap1376(applyARule $ dropReasons gammaWithReasons)1377[ antiARC1378, barbaraARC1379, axiom1380]1381)13821383checkARC :: StopList1384-> Sent1385-> Bool1386checkARC stopList (Sent _ t _) = t `elem` stopList13871388followsInARC :: [String] -> String -> IO ()1389followsInARC gamma phi =1390either1391-- either (\x -> Left ( modelBuildARC stopList x , stopList , map get1 x )) Right1392( \x -> do1393putStrLn $ unlines1394[ "The given sentence is not provable from the assumptions in ARC."1395, ""1396, "Here is a counter-model:"1397, ""1398]1399showCounterModel gamma' phi' x1400putStrLn $ unlines1401[ ""1402, "And here is the list of sentences which do follow, and with restrictions:"1403, ""1404]1405mapM_ (print . get1) x1406putStrLn ""1407)1408( \p -> do1409putStrLn $ unlines1410[ "The sentence follows from the assumptions in ARC."1411, ""1412, "Here is a derivation:"1413, ""1414]1415mapM_ print p1416putStrLn ""1417)1418$ followsInARCUnderRepresentations gamma' phi'1419where1420gamma' = readSs gamma1421phi' = readS phi1422stopList = mkStopList gamma' phi'14231424showCounterModel :: [Sent] -> Sent -> ProofChunk -> IO ()1425showCounterModel gamma phi x =1426showModelNounsVerbsPlusJustificationsARC1427(modelBuildARC stopList x)1428gamma1429phi1430stopList1431where1432stopList = mkStopList gamma phi14331434followsInARCUnderRepresentations :: [Sent] -> Sent -> Either ProofChunk Proof1435followsInARCUnderRepresentations gamma phi =1436findFixedPointOrSat (oneStepARC stopList)1437( \x -> if phi `elem` map get1 x then Just $ numberProof phi x else Nothing1438)1439$ addReasonsToOriginal gamma1440where1441stopList = mkStopList gamma phi14421443numberProof :: Sent -> ProofChunk -> Proof1444numberProof phi = modify . full_reverse . near . tree_reverse . proofSearch phi14451446justCounterModelARC :: [Sent] -> Sent -> Model1447justCounterModelARC gamma phi =1448modelBuildARC stopList1449$ findFixedPoint (oneStepARC stopList)1450$ addReasonsToOriginal gamma1451where1452stopList = mkStopList gamma phi14531454findFixedPointOrSat :: Eq a => (a -> a) -> (a -> Maybe b) -> a -> Either a b1455findFixedPointOrSat f p = loop1456where1457loop x1458| Just y <- p x = Right y1459| x == f x = Left x1460| otherwise = loop $ f x14611462findFixedPoint :: Eq a => (a -> a) -> a -> a1463findFixedPoint f = either id id . findFixedPointOrSat f (\_ -> Nothing)14641465mkStopList :: [Sent] -> Sent -> StopList1466mkStopList gamma phi = nub $ concatMap subterms $ gamma ++ [phi]14671468{-1469countermod :: [Sent]1470-> Sent1471-> StopList1472-> ProofChunk1473-> IO ()1474countermod gamma phi stpList chunk =1475showModelNounsVerbsPlusJustificationsARC m gamma phi stpList -- !!!! PUT THIS BACK FOR the FULL MODELS1476-- showModelNounsVerbsPlusJustificationsARC mShortened gamma phi stpList -- !!! PUT THIS BACK FOR SMALLER MODELS1477where1478m = modelBuildARC stpList chunk -- !!!! USE THIS AND THIS ONLY FOR the FULL MODELS1479-- mShortened = iterativelyShorten m (gamma++[negation phi]) -- !!!! PUT THIS BACK FOR SMALLER MODELS1480-}14811482modelBuildARC :: StopList1483-> ProofChunk1484-> Model1485modelBuildARC stopList chunk = Model1486{ universe = uni1487, cnDict = map1488( \p ->1489M p $ cnInterpretationFn p1490) relevantCNs1491, verbDict = map1492( \transverb ->1493Vb transverb1494$ tvInterpretationFn transverb1495) relVerbs1496}1497where1498uni = [ 0 .. length stopList - 1 ]1499sList = map get1 chunk1500relVerbs = nub $ concatMap verbsIn sList1501relevantCNs = nub $ concatMap cnsIn sList1502order = map pairOfTerms sList1503cnInterpretationFn cn =1504[ r1505| r <- uni1506, (stopList !! r , CNasTerm $ PCN Pos cn) `elem` order1507]1508tvInterpretationFn tv =1509[ (r,s)1510| r <- uni1511, s <- uni1512, (stopList !! r, TermMaker (PV Pos tv) (TermNP All (stopList !! s))) `elem` order1513]1514termInterpretationFn t =1515( t1516, [ r1517| r <- uni1518, (stopList !! r , t) `elem` order1519]1520)15211522pairOfTerms :: Sent -> (Term,Term)1523pairOfTerms (Sent _ t u) = (t,u)15241525-- Here is a test of the main example in Chapter 215261527tSkunks, tMammals, tChordates, tSkunks2 :: Term1528tSkunks = TermMaker sees (TermNP All (CNasTerm skunks) )1529tMammals = TermMaker sees (TermNP All (CNasTerm mammals))1530tChordates = TermMaker sees (TermNP All (CNasTerm chordates))1531tSkunks2 = TermMaker sees (TermNP All tSkunks )15321533testCh2gamma :: [Sent]1534testCh2gamma =1535[ Sent All (CNasTerm skunks) (CNasTerm chordates)1536, Sent All tMammals tSkunks21537, Sent All tSkunks2 (CNasTerm mammals)1538]15391540testCh2phi :: Sent1541testCh2phi = Sent All tSkunks tChordates15421543--followsInARCUnderRepresenatations testCh2phi testCh2gamma15441545tCh2gamma :: [String]1546tCh2gamma =1547[ "all skunks chordates"1548, "all see all mammals see all see all skunks"1549, "all see all see all skunks mammals"1550, "all mammals see all chordates"1551]15521553tCh2phi :: String1554tCh2phi = "all see all skunks see all chordates"15551556tCh2_run :: IO ()1557tCh2_run = followsInARC tCh2gamma tCh2phi15581559-- followsInARC tCh2phi tCh2gamma15601561-- The specific mapping to Chapter 2 is1562-- skunks --> hawks1563---chordates --> birds1564-- mammals -> turtles15651566-- 0 hawks1567-- 1 birds1568-- 2 see all turtles1569-- 3 turtles1570-- 4 see all see all hawks1571-- 5 see all hawks1572-- 6 see all birds1573157415751576-- here there1577--- 0 11578--- 1 61579--- 2 51580--- 31581--- 41582--- 51583--- 615841585test2 :: [M]1586test2 =1587[ M Chordates [3,4]1588, M Birds [1,2,5]1589, M Skunks [2]1590]15911592vTest2 :: [Vb]1593vTest2 =1594[ Vb Sees [(1,2),(1,3), (2,1), (2,5), (3,1), (3,3), (3,4), (3,5), (4,3), (4,4), (5,2), (5,3)],1595Vb Loves [(1,1),(1,2), (1,3), (1,5), (2,1), (3,3), (5,2), (5,5)] ,1596Vb Hates [(2,1),(3,4), (5,1), (5,2), (5,3), (5,4)]1597]15981599model2 :: Model1600model2 = Model1601{ universe = [1,2,3,4,5]1602, cnDict = test21603, verbDict = vTest21604}16051606--- A GOOD TEST IS BELOW1607--- followsInARC "all who see all who hate all skunks see all who love all mammals" ["all mammals hate all skunks", "all skunks see all skunks", "all who love all mammals are skunks", "all boys see all who love all skunks", "all who see all boys are mammals"]16081609-- followsInARC "all who see all who hate all skunks see all who love all mammals" ["all mammals see all skunks", "all skunks see all skunks", "all who love all mammals are skunks", "all boys see all who love all skunks", "all who see all boys are mammals"]16101611-- followsInARC "all who see all who hate all skunks see all who love all mammals" ["all mammals hate all skunks", "all skunks see all skunks", "all who love all mammals are skunks", "all boys see all who love all skunks", "all who see all boys are mammals", "all who see all boys see all skunks", "all who see all skunks love all skunks"]1612161316141615161616171618