-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathProlog.hs
More file actions
273 lines (212 loc) · 9.82 KB
/
Prolog.hs
File metadata and controls
273 lines (212 loc) · 9.82 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
-- Copyright (c) 2009 Takashi Yamamiya
-- Permission is hereby granted, free of charge, to any person obtaining a copy
-- of this software and associated documentation files (the "Software"), to deal
-- in the Software without restriction, including without limitation the rights
-- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-- copies of the Software, and to permit persons to whom the Software is
-- furnished to do so, subject to the following conditions:
-- The above copyright notice and this permission notice shall be included in
-- all copies or substantial portions of the Software.
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-- THE SOFTWARE.
-- | A prolog interpreter.
module Prolog
(-- * Data structures
Term(..), Clause(..),
-- * Utility constructors for debugging
w, s, cons,
-- * Reader
parse, parse',
atom, variable, struct, list, nil, terms, arguments, term, clause, clauses, query,
-- * Printer
display,
-- * Unification
unify, unifyList, applyTerm,
-- * Solver
prove, rename,
-- * Testing
solveString, start) where
import Text.ParserCombinators.Parsec
import Data.Maybe (maybeToList)
import Char (isUpper)
infix 6 :-
data Term = Var String Int | Struct String [Term] deriving (Show, Eq)
data Clause = Term :- [Term] deriving (Show, Eq)
data Command = Fact Clause | Query [Term] | ShowAll | Noop
type Rules = [Clause]
-- Utility constructors for debugging
w :: String -> Term
w s@(x:xs) | isUpper x = Var s 0
| otherwise = Struct s []
s :: String -> [Term] -> Term
s n xs = Struct n xs
cons s cdr = (Struct "cons" [w s, cdr])
---- Unification ----
type Substitution = [(Term, Term)]
true = []
-- | > apply [(w"X", w"Y"), (w"Y", w"Z")] [(w"X"), (w"Y")] == [(w"Z"), (w"Z")]
apply :: Substitution -> [Term] -> [Term]
apply s ts = [applyTerm s t | t <- ts]
applyTerm [] (Var y n) = Var y n
applyTerm ((Var x i, t):s) (Var y j) | x == y && i == j = applyTerm s t
| otherwise = applyTerm s (Var y j)
applyTerm s (Struct n ts) = Struct n (apply s ts)
-- | > unify (w"X") (w"apple") == Just [(w"X", w"apple")]
unify :: Term -> Term -> Maybe Substitution
unify (Var x n) (Var y m) = Just [(Var x n, Var y m)]
unify (Var x n) y = Just [(Var x n, y)]
unify x (Var y m) = Just [(Var y m, x)]
unify (Struct a xs) (Struct b ys)
| a == b = unifyList xs ys
| otherwise = Nothing
unifyList :: [Term] -> [Term] -> Maybe Substitution
unifyList [] [] = Just true
unifyList [] _ = Nothing
unifyList _ [] = Nothing
unifyList (x:xs) (y:ys) = do s <- unify x y
s' <- unifyList (apply s xs) (apply s ys)
return (s ++ s')
---- Solver ----
prove :: Rules -> [Term] -> [Substitution]
prove rules goals = find rules 1 goals
-- Depth first search
-- > find (parse' clauses "p(X):-q(X). q(a).") 1 [parse' term "p(X)"]
find :: Rules -> Int -> [Term] -> [Substitution]
find rules i [] = [true]
find rules i goals = do let rules' = rename rules i
(s, goals') <- branch rules' goals
solution <- find rules (i + 1) goals'
return (s ++ solution)
-- Find next branches. A branch is a pair of substitution and next goals.
-- > branch (parse' clauses "n(z). n(s(X)):-n(X).") (parse' query "?-n(X).")
branch :: Rules -> [Term] -> [(Substitution, [Term])]
branch rules (goal:goals) = do head :- body <- rules
s <- maybeToList (unify goal head)
return (s, apply s (body ++ goals))
-- | Rename all variables in the rules to split namespaces.
rename :: Rules -> Int -> Rules
rename rules i = [ renameVar head :- renameVars body | head :- body <- rules]
where renameVar (Var s _) = Var s i
renameVar (Struct s ts) = Struct s (renameVars ts)
renameVars ts = [renameVar t | t <- ts]
---- Reader ----
-- Spaces are always consumed with the previous token.
parse' parser s = result where Right result = parse parser "" s
nil = Struct "nil" []
schar c = char c >> spaces
special = oneOf ":;+=-*&$#@/.~!" <|> digit
atom = (lower >>= \x -> many alphaNum >>= \xs -> spaces >> return (x:xs)) <|>
(many1 special >>= \x -> spaces >> return x)
variable = upper >>= \x -> many alphaNum >>= \xs -> spaces >> return (Var (x:xs) 0)
struct = atom >>= \name -> arguments >>= \ls -> return (Struct name ls)
arguments = ((schar '(' >> terms >>= \ls -> schar ')' >> return ls)) <|>
(spaces >> return [])
list = schar '[' >> terms >>= \ts -> listTail >>= \t -> return (makeList ts t)
where makeList [] cdr = cdr
makeList (x:xs) cdr = Struct "cons" [x, makeList xs cdr]
listTail = (schar '|' >> term >>= \t -> schar ']' >> return t) <|>
(schar ']' >> return nil)
term = (variable <|> struct <|> list) >>= \t -> return t
terms = sepBy term (schar ',')
clause = struct >>= \head -> ((schar '.' >> return (head :- [])) <|>
(query >>= \goals -> return (head :- goals)))
clauses = many clause
arrow = (char '?' <|> char ':') >> schar '-'
query = arrow >> terms >>= \goals -> schar '.' >> return goals
noop = (char '%' >> skipMany anyToken) <|> eof
command :: Parser Command
command = spaces >>
((clause >>= \c -> return (Fact c)) <|>
try (query >>= \ts -> return (Query ts)) <|>
(string "??" >> return (ShowAll)) <|>
(noop >> return (Noop)))
-- parse atom "" "atom1234"
-- parse variable "" "Variable1234"
-- parse struct "" "father ( masuo , tara ) "
-- parse arguments "" "( orange , Apple , banana ) "
-- parse list "" "[]"
-- parse list "" "[ 1 , 2 | 3 ] "
-- parse terms "" "orange , apple , banana "
-- parse term "" "someAtom "
-- parse clause "" "child ( X , Y) :- mother( Y, X ) . "
-- parse query "" "?- apple ."
---- Printer ----
class Display a where
displays :: a -> String -> String
display :: a -> String
display x = displays x ""
instance Display Term where
displays (Var s 0) = showString s
displays (Var s n) = showString s . showChar '_' . shows n
displays (Struct "nil" []) = showString "[]"
displays (Struct "cons" [h, t]) = showChar '[' . displays h . displaysTail t . showChar ']'
displays (Struct s []) = showString s
displays (Struct s xs) = showString s . showChar '(' . displays xs . showChar ')'
displaysTail (Struct "nil" []) = id
displaysTail (Struct "cons" [h, t]) = showChar ',' . displays h . displaysTail t
displaysTail x = showChar '|' . displays x
instance Display Clause where
displays (head :- []) = displays head . showChar '.'
displays (head :- bodies) = displays head . showString " :- " . displays bodies . showChar '.'
instance Display a => Display [a] where
displays [] = id
displays [x] = displays x
displays (x:xs) = displays x . showChar ',' . displays xs
instance (Display a, Display b) => Display (a, b) where
displays (x, y) = displays x . showChar '=' . displays y
displayLines [] = ""
displayLines (x:xs) = display x ++ "\n" ++ display xs
-- display (s"cons" [w"1", (s"cons" [w"2", nil])])
-- display ((s"child" [w"X",w"Y"]) :- [s"mother" [w"Y",w"X"]])
---- REPL --
main = interact start
start = writeStr ("food(apple). -- Add a clause.\n" ++
"?- food(X). -- Query.\n" ++
"?? -- Show all.\n\n") (loop [])
loop :: Rules -> String -> String
loop rules = readLine (exec rules . parse command "")
exec :: Rules -> Either ParseError Command -> String -> String
exec rules (Right (Fact c)) = writeStr ("=> " ++ display c ++ "\n" ) (loop (rules ++ [c]))
exec rules (Right (Query q)) = answer q (prove rules q) rules
exec rules (Right ShowAll) = writeStr (showAll rules) (loop rules)
exec rules (Right Noop) = loop rules
exec rules (Left e) = writeStr (show e ++ "\n") (loop rules)
answer :: [Term] -> [Substitution] -> Rules -> String -> String
answer q [] rules = writeStr "No\n" (loop rules)
answer q (c:cs) rules = writeStr ("=> " ++ result ++ "\n") (more q cs rules)
where result = display (apply c q)
more :: [Term] -> [Substitution] -> Rules -> String -> String
more q cs rules = readLine f
where f (';':_) = answer q cs rules
f x = writeStr "Yes\n" (loop rules)
showAll rules = [line | r <- rules, line <- "=> " ++ display r ++ "\n" ]
-- Interactive library
-- Its arguments are a string to be written and next process.
writeStr :: String -> (String -> String) -> (String -> String)
writeStr output proc input = output ++ proc input
-- Its argument is a process which receives a line.
readLine :: (String -> (String -> String)) -> (String -> String)
readLine proc input = case (nextLine input) of
("", []) -> "" -- End of file
(line, rest) -> proc line rest
nextLine "" = ("","")
nextLine ('\n':xs) = ("\n", xs)
nextLine (x:xs) = (x:ys, zs) where (ys, zs) = nextLine xs
---- Testing ----
-- | Test function
--
-- >>> solveString "p:-q. q:-r. r." "?-p."
-- > [[]]
-- >>> solveString' "p(X):-q(X).q(a)." "?-p(X)."
-- > ["X=X_1,X_1=a"]
solveString :: String -> String -> [Substitution]
solveString rules q =
let rules' = parse' clauses rules
q' = parse' query q
in prove rules' q'
solveString' rules q = [display s | s <- solveString rules q]