Вы находитесь на странице: 1из 60

# What is AI? Explain AI problem 012 1B What is depth first search?

Explain algorithm and advantages 033 2A what is representation and reasoning 064 2B explain the term iteration and recursion related to AI 075 3A explain water jug problem 126 3B solve the problem by decomposable method sin2xcos2dx 147 4A explain any four built in functions of lisp 54solved in2007 oldsyllabus8 4B what is predicates in lisp explain any two 159 5A write a lisp program to fib Fibonacci series 1710 5B write a lisp program to find a factorial of a given number 1811 6A briefly explain the structure of a prolog program 1912 6B write the step procedure to compile and execute a program 2113 7 explain the following with examplei. null -22 ii. setf - 23 iii. Format - 24 iv. Cons - 252214 8A write a lisp program to find frequency of a number in a sinenlist2715 8B What is recursion? Write a program using recursive conceptto find sun of natural number28 SN Q QUESTION P. NO 16 1.A it is useful to structure AI. Production system provide such structure?discuss in detail3017 1.B Explain various characteristics of problem 3218 2.A explain state space representation for water jug problem 3619 2.B differentiate between depth first versus breadth first search method 3920 3.A what is heuristics? Explain any heuristic search method 4021 3.B define matching. Explain any one matching technique 4222 4.A how do you represent the knowledge using predicate logic 4323 4.B discuss unification algorithm 4724 5.A define predicate an objects in prolog. Discuss various types of objects usedin prolog4925 5.B write a prolog program to generate Fibonacci series 52R 6.A explain various list processing functions of LISP 5426 6.B write a program in LISP to find the factorial of a given number Ni. without recursion 57 ii. with recursion 60 5727 7.A write a prolog program to verify username and password 6128 7.B list the similarities and differences between prolog and conventional programming languages6229 8 write a short notes ona. forward versus backward reasoning b. structure of prolog program repeated in 2007 c. characteristics of knowledge 66 d. syntax and semantics of propositional logic 66 64 SN Q QUESTION P. NO REPEATED IN30 1.A What is AI? Explain different AI techniques 7231 1.B explain application area of AI 732.A explain production system in detail 2007 old syllabus32 2.B discuss traveling salesmans problem 753.A discuss state space representation for water jug problem 2007 old syllabus3.B Explain any heuristic research method 2007 old syllabus4.A explain various characteristics of problem 2007 old syllabus4.B list the various differences between depth first and breadth firstsearch method2007 old syllabus5.A explain structures of a prolog program 20075.B write a prolog program to generate Fibonacci numbers 2007 old syllabus33 6.A write a prolog program to find sun of n natural numbers 786.B write the similarities and differences between prolog andconventional programming languages2007 old syllabus7.A write various list processing function of LISP 2007 old syllabus34 7.B write a program in LISP to find the largest of three numbers 798 write short notes on any two of the followingi. forward verses backward reasoningii. characteristics of knowledgeiii. syntax and semantics of propositional logic2007

As Im not handling this subject, I cant guarantee the accuracy of every answer--- Read on your own risk!!!Solved by SURESH the SUN , lecturer at BCA dept, SG College Campus --- Koppal pg. no: 1 Artificial intelligence 2007 1. 1.A WHAT IS AI? EXPLAIN AI PROBLEM AI is The branch of computer science concerned with making computers behave like humans. The term wascoined in 1956 by John McCarthy at the Massachusetts Institute of Technology.includes Artificial intelligence includes: games playing: programming computers to play games such as chess and checkers expert systems : programming computers to make decisions in real-life situations (for example, someexpert systems help doctors diagnose diseases based on symptoms) natural language : programming computers to understand natural human languages neural networks : Systems that simulate intelligence by attempting to reproduce the types of physicalconnections that occur in animal brains robotics : programming computers to see and hear and react to other sensory stimuliCurrently, no computers exhibit full artificial intelligence (that is, are able to simulate human behavior). Thegreatest advances have occurred in the field of games playing. The best computer chess programs are nowcapable of beating humans. In May, 1997, an IBM super-computer called Deep Blue defeated world chesschampion Gary Kasparov in a chess match.In the area of robotics, computers are now widely used in assembly plants, but they are capable only of verylimited tasks. Robots have great difficulty identifying objects based on appearance or feel, and they still moveand handle objects clumsily. Natural-language processing offers the greatest potential rewards because it would allow people to interact with computers withoutneeding any specialized knowledge. You could simply walk up to a computer and talk to it. Unfortunately, programming computers tounderstand natural languages has proved to be more difficult than originally thought. Some rudimentary translation systems thattranslate from one human language to another are in existence, but they are not nearly as good as human translators. There are alsovoice recognition systems that can convert spoken sounds into written words, but they do not understand

And there is no guarantee to find a minimal solution, if more than one solution exists. As Im not handling this subject, I cant guarantee the accuracy of every answer--- Read on your own risk!!!Solved by SURESH the SUN , lecturer at BCA dept, SG College Campus --- Koppal pg. no: 4 ANSWER 2: Formally, DFS is an uninformed search that progresses by expanding the first child node of thesearch tree that appears and thus going deeper and deeper until a goal node is found, or until it hits anode that has no children. Then the search backtracks, returning to the most recent node it hasn'tfinished exploring. In a non-recursive implementation, all freshly expanded nodes are added to astack for exploration. The depth-first search explores each possible path to its conclusion before another path is tried. To understandexactly how this works, consider the tree that follows. F is the goal.A depth-first search traverses the graph in the following order: ABDBEBACF. If you are familiar with trees,you recognize this type of search as an inorder tree traversal. That is, the path goes left until a terminal node isreached or the goal is found. If a terminal node is reached, the path backs up one level, goes right, and then leftuntil either the goal or a terminal node is encountered. This procedure is repeated until the goal is found or thelast node in the search space has been examined.EXAMPLE:For the following graph:a depth-first search starting at A, assuming that the left edges in the shown graph are chosen before right edges,and assuming the search remembers previously-visited nodes and will not repeat them (since this is a smallgraph), will visit the nodes in the following order: A, B, D, F, E, C, G. The edges traversed in this search form aTrmaux tree, a structure with important applications in graph theory. As Im not handling this subject, I cant guarantee the accuracy of every answer--- Read on your own risk!!!Solved by SURESH the SUN , lecturer at BCA dept, SG College Campus --- Koppal pg. no: 5Performing the same search without remembering previously visited nodes results in visiting nodes in the order A, B, D, F, E, A, B, D, F, E, etc. forever, caught in the A, B, D, F, E cycle and never reaching C or G.Iterative deepening is one technique to avoid this infinite loop and would reach all nodes. DFS ALGORITHM A DFS algorithm, as the name implies, is used to search deeper in the graph, whenever possible. The edges areexplored, out of the most recently discovered vertex v that still has unexplored edges leaving it. When all of v 'sedges have been explored, the search backtracks to explore edges leaving the vertex from which v wasdiscovered. This process continues until we have discovered all the vertices that are reachable from the sourcevertex. DFS uses stack structure to maintain the order in which the vertices are to be processed. Algorithm: Step 1: Initialize all nodes to ready state (status = 1)Step 2: Push the starting node in stack and change its status to the waiting state (status = 2)Step 3: Repeat step 4 and 5 until stack is emptyStep 4: pop the top node n of stack. Process n and change the status of n to the processed state (status = 3)Step 5: Push on to the stack, all the neighbor of n

that are in ready state (status = 1), and change their status tothe waiting state (status = 2) [End of the step 3 loop]Step 6: exit APPLICATIONS OF DFS ALGORITHM Finding connected components. Topological sorting. Finding 2-(edge or vertex)-connected components. Finding 3-(edge or vertex)-connected components. Finding the bridges of a graph. Finding strongly connected components. Planarity Testing [1][2] Solving puzzles with only one solution, such as mazes. (DFS can be adapted to find all solutions to amaze by only including nodes on the current path in the visited set.) Maze generation may use a randomized depth-first search. Finding biconnectivity in graphs. As Im not handling this subject, I cant guarantee the accuracy of every answer--- Read on your own risk!!!Solved by SURESH the SUN , lecturer at BCA dept, SG College Campus --- Koppal pg. no: 6 2. 2.A WHAT IS REPRESENTATION AND REASONING is an area of artificial intelligence research aimed at representing knowledge in symbols to facilitate inferencingfrom those knowledge elements, creating new elements of knowledge. The KR can be made to be independentof the underlying knowledge model or knowledge base system (KBS) such as a semantic network. [1] A knowledge representation (KR) is most fundamentally a surrogate, a substitute for the thing itself,used to enable an entity to determine consequences by thinking rather than acting, i.e., by reasoningabout the world rather than taking action in it. It is a set of ontological commitments, i.e., an answer to the question: In what terms should I think aboutthe world? It is a fragmentary theory of intelligent reasoning, expressed in terms of three components: (i) therepresentation's fundamental conception of intelligent reasoning; (ii) the set of inferences therepresentation sanctions; and (iii) the set of inferences it recommends. It is a medium for pragmatically efficient computation, i.e., the computational environment in whichthinking is accomplished. One contribution to this pragmatic efficiency is supplied by the guidance

arepresentation provides for organizing information so as to facilitate making the recommendedinferences. It is a medium of human expression, i.e., a language in which we say things about the world."Some issues that arise in knowledge representation from an AI perspective are: How do people represent knowledge? What is the nature of knowledge? Should a representation scheme deal with a particular domain or should it be general purpose? How expressive is a representation scheme or formal language? Should the scheme be declarative or procedural? Characteristics A good knowledge representation covers six basic characteristics: Coverage, which means the KR covers a breath and depth of information. Without a wide coverage, theKR cannot determine anything or resolve ambiguities. Understandable by humans. KR is viewed as a natural language, so the logic should flow freely. Itshould support modularity and hierarchies of classes (Polar bears are bears, which are animals). Itshould also have simple primitives that combine in complex forms. Consistency. If John closed the door, it can also be interpreted as the door was closed by John. By beingconsistent, the KR can eliminate redundant or conflicting knowledge. Efficient Easiness for modifying and updating. Supports the intelligent activity which uses the knowledge base As Im not handling this subject, I cant guarantee the accuracy of every answer--- Read on your own risk!!!Solved by SURESH the SUN , lecturer at BCA dept, SG College Campus --- Koppal pg. no: 7 this program has a long history of work in the following areas: Generative planning Reactive planning/control Fuzzy control Evidential reasoning Structured argumentation Automated deduction

10 334 ticks 11 ticks 100 846 ticks 23 ticks 1000 3368 ticks 110 ticks 10000 9990 ticks 975 ticks 100000 stackoverflow 9767 ticks As we can clearly see the recursive is a lot slower than the iterative (considerably) and limiting (stackoverflow). The reason for the poor performance is heavy push-pop of the registers in the IL level of each recursive call. Fibonacci: As Im not handling this subject, I cant guarantee the accuracy of every answer--- Read on your own risk!!!Solved by SURESH the SUN , lecturer at BCA dept, SG College Campus --- Koppal pg. no: 11 //--------------- iterative version ---------------------static int FibonacciIterative(int n){if (n == 0) return 0;if (n == 1) return 1;int prevPrev = 0;int prev = 1;int result = 0;for (int i = 2; i <= n; i++){result = prev + prevPrev;prevPrev = prev;prev = result;}return result;}//--------------- naive recursive version --------------------static int FibonacciRecursive(int n){if (n == 0) return 0;if (n == 1) return 1;return FibonacciRecursive(n - 1) +FibonacciRecursive(n - 2);}//--------------- optimized recursive version --------------------static Dictionary resultHistory =new Dictionary();static int FibonacciRecursiveOpt(int n){if (n == 0) return 0;if (n == 1) return 1;if (resultHistory.ContainsKey(n))return resultHistory[n];int result = FibonacciRecursiveOpt(n - 1) +FibonacciRecursiveOpt(n - 2);resultHistory[n] = result;return result;}Remark: in this test I don't look at the results because int isn't capable of holdingsuch big numbers. N Recursive Recursive opt. Iterative 5 5 ticks 22 ticks 9 ticks 10 36 ticks

49 ticks 10 ticks 20 2315 ticks 65 ticks 10 ticks 30 180254 ticks 61 ticks 9 ticks 100 Too long/overflow 158 ticks 11 ticks 1000 Too long/overflow 1470 ticks 27 ticks 10000 Too long/overflow 13873 ticks 190 ticks 100000 Too long/overflow Too long/overflow 3952 ticks As Im not handling this subject, I cant guarantee the accuracy of every answer--- Read on your own risk!!!Solved by SURESH the SUN , lecturer at BCA dept, SG College Campus --- Koppal pg. no: 12 As before the recursive approach is worse than iterative however, we could apply memoization pattern(saving previous results in dictionary for quick key based access), although this pattern isn't match for iterativeapproach (but definitely improvement over the simple recursion).Summery 1. Try not to use recursion in system critical locations 2. Elegant solutions not always the best performing when used in "recursive situations". 3. If you required to use recursion at least try to optimize it with dynamic programming approaches(such as memoization) 3. 3.A EXPLAIN WATER JUG PROBLEM

to the earlier state fromwhich we came to the current state, if current state seems to be less desirable than the earlier state. The 8-puzzleproblem has recoverable steps, or, we may say the problem is a recoverable problem.c) However if we are playing chess, then a wrong step may not be evenrecoverable. In other words, we may not be in a position, because of the adversarys move, to move back to earlier state.Such a problem is called an irrecoverable problem.Depending on the nature of the problem as ignorable-step, recoverable-step or irrecoverable step problem, we have tochoose our tools, techniques and strategies for solving the problem.<!--[if !supportLineBreakNewLine]--><!--[endif]--> There are many other characteristics of a problem viz., Whether the problem has certain outcome or uncertain outcome As Im not handling this subject, I cant guarantee the accuracy of every answer--- Read on your own risk!!!Solved by SURESH the SUN , lecturer at BCA dept, SG College Campus --- Koppal pg. no: 15 Whether a good solution is absolute or relative Whether the solution is a state or a path Whether the problem essentially requires interaction with the user etc.Which can be known through analyzing the problem under consideration, and the knowledge of which, in turn, may helpus in determining or guessing a correct sequence of actions for solving the problem under consideration.Analysing an algorithm: It is used to determine the requirement of computer resources for each algorithm. And then, if there are more than one algorithms that solve a problem, the analysis is also concerned with choosing the better one onthe basis of comparison of requirement of resources for different available algorithms. The lesser the requirement better the algorithm. The resources that are taken into consideration for analysing algorithms, include(i) Time expected to be taken in executing the instances of the problem generally as a function for the size of the instance.(ii) Memory space expected to be required by the computer system, in executing the instances of the problem, generallyas a function of the size of the instances.(iii) Also sometimes, the man-hour or man-month taken by the team developing the program is also taken as a resourcefor the purpose. 4. 4.A EXPLAIN ANY FOUR BUILT IN FUNCTIONS OF LISP? >>>REPEATED IN 2007 OLD SYLLABUS, PLEASE REFER PAGE NO 544.B WHAT IS PREDICATES IN LISP EXPLAIN ANY TWO A predicate is a function used to test for some condition involving its arguments and returns nil if thecondition is false, or some non-nil value if the condition is true. Name of the predicates in CL usually ends with p.Ex: numberp, standard-char-p etc. overviewLogical valuesData Type predicatesGeneral Type PredicatesSpecific data type predicatesEquality predicatesLogical operators Logical valuesThe names nil and t are constants in LispThis object represents logical false value and also the empty list.It can also be written as ()The values of nil and t are not permitted to be changed.Data type predicates:using data type predicates one can determinewhether or not it belongs to a given type, or onecan compare two type specifies. General Type predicatesSyntax:typep object type As Im not handling this subject, I cant guarantee the accuracy of every answer--- Read on your own risk!!!Solved by SURESH the SUN , lecturer at BCA dept, SG College Campus --- Koppal pg. no: 16Typep is the predicate that is true if the object is of type type false otherwise.

Subtypep type1 type2 This predicate returns T if type1 is a subtype of type1 else it returns nil.returns T Ex: (subtypep t t) Subtypep are supposed to return a second value of nil unless one or both of its arguments involves satisfiesand, or, not or member.Subtypep should signal an error when one or both of its arguments involves values or the list form of thefunction type specifier Subtypep must always return the two values t and t in the case where its arguments, after expansion of specifiesdefined by deftype are equal.(subtypep (array A) (array B)) is true if and only if (upgraded-array-element-type A) is the same type as(upgraded-array-element-type b)(subtypep (complex A) (complex B)) is true if and only if (upgraded-complex-part-type A) and (upgraded-complex-part-type B) is of same type. Specific data type predicatesThe following data types test for specific individual data types.returns true if the argument is () or false otherwise. null objectreturns true if the argument is a symbol else returns false symbolp objectis true if the argument is not cons otherwise its false. atom objectis true if the argument is a cons, false otherwise consp objectis true if the argument is a cons or an empty list (), false otherwise listp objectis T if the argument is any kind of number Numberp object is T if the argument is a rational number false otherwise Rationalp objectSimilarly we have floatp, charaterp, vectorp, stringp, complexp, simple-bit-vector-p, simple-string-vector-p,arrayp etc.is T if its argument is a package and otherwise is false packagep objectfunctionp is T if its arguments are suitable for applying to arguments, object using for ex the funccall or applyfunction and otherwise is falseis T if its argument is any compiled code object and otherwise is false Compiled-function-p objectis T if its argument is any standard CL data type, and otherwise is false Commonp object Equality predicatesCl provides these predicates to test for the equality of the two objects: eq, eql, equal, equalpis true if and only if x and y are the same identical objects. eq x yfalse Ex: (eq g h)true (eq 3 3)false

(eq hi HI)Eql is true if the arguments are eq, or of there are numbers of the x y same type with the same value, or if thereare character objects that represent the same character is true if the arguments are structurally similar objects. (isomorphic objects) equal x ytrue Ex: (equal #B #B)true (equal FOO FOO)is true if the two objects are equal, and if and only if they are eq that is, the same identical object. equalp x ytwo hash tables are considered the same by equalp if and only if they satisfy the following four conditions: They must be of the same kind ( equivalent :test arguments must be given to make hash-table when thetwo hash-tables are created. As Im not handling this subject, I cant guarantee the accuracy of every answer--- Read on your own risk!!!Solved by SURESH the SUN , lecturer at BCA dept, SG College Campus --- Koppal pg. no: 17 They must have the same number of entries. For every entry(key1, value1) in one hash table there must be the corresponding entry(key2, value2) inthe other hash table. For every entry(key1, value1) in one hash table and its corresponding entry(key2, value2) in the other ,such that key1 and key2 are the same, equalp must be true of value1 and value2. Logical operatorsCL provides three operators as Boolean value: and, or, and notEx: not y Returns t if y is nil else returns nil.And returns t if the condition is true else NIL.Ex: (and form1, form2,) Evaluates each form one at the time from left to right. If at least one form returns a nil, the evaluation isstopped by returning a nil.Ex: (and (< 1 2)(< 3 4)(princ true))true true Or operator returns NIL for false conditions and true conditions return non-nil characters(or form1,form2,..) Performs or operation the forms one by one from left to right. It is true if at least one of the forms aretrueEx; (or (< 3 1)(> 2 1))T 5. 5.A WRITE A LISP PROGRAM TO FIND FIBONACCI SERIES

Fact: ... . o Rule: ... :- ... . o Query: ?- ... . o Variables: must begin with an upper case letter. o Constants: numbers, begin with lowercase letter, or enclosed in single quotes. Inductive definitions: base and inductive cases o Towers of Hanoi: move N disks from pin a to pin b using pin c.hanoi(N) :- hanoi(N, a, b, c).hanoi(0,_,_,_).hanoi(N,FromPin,ToPin,UsingPin) :- M is N1,hanoi(M,FromPin,UsingPin,ToPin),move(FromPin,ToPin),hanoi(M,UsingPin,ToPin,FromPin).move(Fr om,To) :- write([move, disk from, pin, From, to, pin, ToPin]),nl. o Lists: append, member As Im not handling this subject, I cant guarantee the accuracy of every answer--- Read on your own risk!!!Solved by SURESH the SUN , lecturer at BCA dept, SG College Campus --- Koppal pg. no: 20list([]).list([X|L]) :- [list(L).Abbrev: [X 1 |[...[X n |[]...] = [X 1 ,...X n ]append([],L,L).append([X|L1],L2,[X|L12]) :- append(L1,L2,L12).member(X,L) :- concat(_,[X|_],L). o Ancestor ancestor(A,D) :- parent(A,B).ancestor(A,D) :- parent(A,C),ancestor(C,D). but not ancestor(A,D) :- ancestor(A,P), parent(P,D). since infinite recursion may result. Depth-first search: Maze/Graph traversalA database of arcs (we will assume they are directed arcs) of the form:a(node_i,node_j).Rules for searching the graph:go(From,To,Trail).go(From,To,Trail) :- a(From,In), not visited(In,Trail), go(In,To,[In|Trail]).visited(A,T) :- member(A,T). I/O: terms, characters, files, lexical analyzer/scanner o read(T), write(T), nl. o get0(N), put(N): ascii value of character o name(Name,Ascii_list). o see(F), seeing(F), seen, tell(F), telling(F), told.

trace ; to end tracing, use notrace . To exit Prolog, use halt . As Im not handling this subject, I cant guarantee the accuracy of every answer--- Read on your own risk!!!Solved by SURESH the SUN , lecturer at BCA dept, SG College Campus --- Koppal pg. no: 22 7. EXPLAIN THE FOLLOWING WITH EXAMPLEi. NULL ii. SETF iii. FORMAT iv. CONSi. null In Lisp, functions can gracefully accept the special object nil , which reduces the amount of special case testingin application code. For instance although nil is an atom and does not have any fields, the functions car and cdr accept nil and just return it, which is very useful and results in shorter code.Since nil is the empty list in Lisp, the situation described in the introduction above doesn't exist. Code whichreturns nil is returning what is in fact the empty list (and not anything resembling a null reference to a listtype), so the caller does not need to test the value to see whether or not it has a list.The null object pattern is also supported in multiple value processing. If the program attempts to extract a valuefrom an expression which returns no values, the behavior is that the null object nil is substituted. Thus (list(values)) returns (nil) (a one-element list containing nil). The (values) expression returns no values at all, but since the function call to list needs to reduce its argument expression to a value, the null object isautomatically substituted. CLOS In Common Lisp, the object nil is the one and only instance of the special class null . What this means is that amethod can be specialized to the null class, thereby implementing the null design pattern. Which is to say, it isessentially built into the object system:

;; empty dog class(defclass dog () ());; a dog object makes a sound by barking: woof! is printed on standard output;; when (make-sound x) is called, if x is an instance of the dog class.(defmethod makesound ((obj dog))(format t "woof!~%"));; allow (make-sound nil) to work via specialization to null class.;; innocuous empty body: nil makes no sound.(defmethod make-sound ((obj null))) The class null is a subclass of the symbol class, because nil is a symbol. Since nil also represents the emptylist, null is a subclass of the list class, too. Methods parameters specialized to symbol or list will thus take a nil argument. Of course, a null specialization can still be defined which is a more specific match for nil . As Im not handling this subject, I cant guarantee the accuracy of every answer--- Read on your own risk!!!Solved by SURESH the SUN , lecturer at BCA dept, SG College Campus --- Koppal pg. no: 23 ii. setf Setf Certain forms in LISP naturally define a memory location. For example, if the value of x is a structure of type foo , then (foo-bar x) defines the bar field of the value of x . Or, if the value of y is a one-dimensional array, (aref y 2) defines the third element of y .The

setf special form uses its first argument to define a place in memory, evaluates its second argument, andstores the resulting value in the resulting memory location. For example, > (setq a (make-array 3))#(NIL NIL NIL)> (aref a 1)NIL> (setf (aref a 1) 3)3> a#(NIL 3 NIL)> (aref a 1)3> (defstruct foo bar)FOO> (setq a (make-foo))#s(FOO :BAR NIL)> (foo-bar a)NIL> (setf (foo-bar a) 3)3> a#s(FOO :BAR 3)> (foo-bar a)3Setf is the only way to set the fields of a structure or the elements of an array.Here are some more examples of setf and related functions. > (setf a (make-array 1)) ;setf on a variable is equivalent to setq#(NIL)> (push 5 (aref a 1)) ;push can act like setf(5)> (pop (aref a 1)) ;so can pop5> (setf (aref a 1) 5)5> (incf (aref a 1)) ;incf reads from a place, increments,6 ;and writes back> (aref a 1)6 As Im not handling this subject, I cant guarantee the accuracy of every answer--- Read on your own risk!!!Solved by SURESH the SUN , lecturer at BCA dept, SG College Campus --- Koppal pg. no: 24 iii. format Lisp's FORMAT function is analogous to C's printf function, but FORMAT can do a whole lot more. FORMAT can iterate, use conditionals, process nested format strings, & recurse into format strings embedded into itsarguments.The more-or-less official documentation for FORMAT is at the Common Lisp Hyperspec. There is a complete if terse description of it in Paul Graham's ANSI Common Lisp, but my favorite description of FORMAT is inFranz's Common Lisp The Reference.Knowing the details of how something works isn't the same as knowing how to use it well. Good applications of FORMAT aren't obvious from its documentation. Thus this article.Let's say you have a list containing the data for one row in a table, & you want to use FORMAT to print that row.In other words, you have something like this: (1 green ribbit) and you want to print something like this: number color noise------ -------- --------1 green ribbit Notice that the third line, which has ``green'' & ``ribbit'' in it, is from the list that we have.The first column has a width of six; the second & third columns have widths of eight. The first column is prefixed by three spaces. The columns are separated by two spaces.Here's one way to print that line, assuming the data for the row is in a list called ROW : (format t "~& ~6D ~8A ~8A"(first row) (second row) (third row)) Here are some examples, using NIL

so that FORMAT will return strings. > (setq row (list 1 'green 'ribbit))(1 GREEN RIBBIT)> (format nil "~& ~6D ~8@A ~8@A"(first row) (second row) (third row))" 1 GREEN RIBBIT" It's a bummer that we have to separate the list into parts before calling FORMAT . We could avoid that byapplying APPLY to the situation, but that would require more typing & some cons ing. A better (but not verygood) way to make FORMAT do that work with the ~? directive, like this: > (format nil "~?""~& ~6D ~8@A ~8@A"row)" 1 GREEN RIBBIT" A better way to make FORMAT do the work is with the ~{ directive. As Im not handling this subject, I cant guarantee the accuracy of every answer--- Read on your own risk!!!Solved by SURESH the SUN , lecturer at BCA dept, SG College Campus --- Koppal pg. no: 25 > (format nil "~& ~{~6D ~8@A ~8@A~}" row)" 1 GREEN RIBBIT" This is the best way I know so far to print a single row if you have the items of a row in a list.There's one more twist: What if the row list contains an item we don't want to print? We can use the ~* directiveto skip the items we don't want to print. > (format nil "~& ~{~6D ~*~8@A ~8@A~}"(list 2 'skip-me 'yellow 'buzz))" 2 YELLOW BUZZ" If you want to print an entire table or report, iv. cons In computer programming, cons

ns/) is a fundamental function in most dialects of the Lisp programming language. cons cons tructs memory objects which hold two values or pointers to values. Theseobjects are referred to as (cons) cells, conses, non-atomic s-expressions ("NATSes"), or (cons) pairs. In Lisp jargon, the expression "to cons x onto y " means to construct a new object with

(cons x y ) . The resulting pair has a left half, referred to as the car (the first element), and a right half (the second element), referred to as the cdr .It is loosely related to the object-oriented notion of a constructor, which creates a new object given arguments,and more closely related to the constructor function of an algebraic data type system.The word "cons" and expressions like "to cons onto" are also part of a more general functional programming jargon. Sometimes operators that have a similar purpose, especially in the context of list processing, are pronounced "cons". (A good example is the :: operator in ML and Scala, which adds an element to the beginning of a list.) Use : Although cons cells can be used to hold ordered pairs of simplex data, they are more commonly used toconstruct more complex compound data structures, notably lists and binary trees.For example, the Lisp expression (cons 1 2) constructs a cell holding 1 in its left half (the so-called car field)and 2 in its right half (the cdr field). In Lisp notation, the value (cons 1 2) looks like: (1 . 2) Note the dot between 1 and 2; this indicates that the S-expression is a "dotted pair," rather than a "list." Lists Cons cell diagram for the list (42 69 613), written with cons : (cons 42 (cons 69 (cons 613 nil))) and written with list : As Im not handling this subject, I cant guarantee the accuracy of every answer--- Read on your own risk!!!Solved by SURESH the SUN , lecturer at BCA dept, SG College Campus --- Koppal pg. no: 26 (list 42 69 613)In Lisp, lists are implemented on top of cons pairs. More specifically, any liststructure in Lisp is either: 1. An empty list () , which is a special object usually called nil .2. A cons cell whose car

is the first element of the list and whose cdr is a list containing the rest of theelements.This forms the basis of a simple, singly linked list structure whose contents can be manipulated with cons , car , and cdr . Note that nil is the only list that is not also a cons pair. As an example, consider a list whoseelements are 1, 2, and 3. Such a list can be created in three steps:1. Cons 3 onto nil , the empty list2. Cons 2 onto the result3. Cons 1 onto the resultwhich is equivalent to the single expression: (cons 1 (cons 2 (cons 3 nil))) or its shorthand:(list 1 2 3)The resulting value is the list: (1 . (2 . (3 . nil))) i.e. i.e *--*--*--nil| | |1 2 3 which is generally abbreviated as: (1 2 3) Thus, cons can be used to add one element to the front of an existing linked list. For example, if x is the list wedefined above, then (cons 5 x ) will produce the list: (5 1 2 3) Another useful list procedure is append , which concatenates two existing lists (i.e. combines two lists into asingle list). Trees Binary trees that only store data in their leaves are also easily constructed with cons . For example, the code: (cons (cons 1 2) (cons 3 4)) As Im not handling this subject, I cant guarantee the accuracy of every answer--- Read on your own risk!!!Solved by SURESH the SUN , lecturer at BCA dept, SG College Campus --- Koppal pg. no: 27results in the tree: ((1 . 2) . (3 . 4)) i.e. */ \* */ \ / \1 2 3 4

Technically, the list (1 2 3) in the previous example is also a binary tree, one which happens to be particularlyunbalanced. To see this, simply rearrange the diagram: *--*--*--nil| | |1 2 3 to the following equivalent: */ \1 */ \2 */ \3 nil Use in conversation Cons can refer to the general process of memory allocation, as opposed to using destructive operations of thekind that would be used in an imperative programming language.For example: I sped up the code a bit by putting in side effects instead of having it cons like crazy. 8. 8.A WRITE A LISP PROGRAM TO FIND FREQUENCY OF A NUMBER INA SINEN LISTLOGIC: (defun sum (L)(reduce '+ L))(sum '(1 2 3))6 This works: (+ 1 2 3)6 This doesn't work: (+ '(1 2 3)) This works if ' cl-* ' is loaded: As Im not handling this subject, I cant guarantee the accuracy of every answer--- Read on your own risk!!!Solved by SURESH the SUN , lecturer at BCA dept, SG College Campus --- Koppal pg. no: 28 (reduce '+ '(1 2 3)) 6 8.B WHAT IS RECURSION? WRITE A PROGRAM USING RECURSIVECONCEPT TO FIND SUN OF NATURAL NUMBER A recursive function contains code that tells the Lisp interpreter to call a program that runs exactly likeitself, but with slightly different arguments. The code runs exactly the same because it has the same name.However, even though the program has the same name, it is not the same entity. LISP has no loop constructs, so recursion is the only way to process data. A recursive function is a functionwhich calls itself. This technique recognises that an operation on some data may be best expressed as theaggregate of the same operation performed on each item of data of which it is comprised. Obviously thistechnique is best used with data structures which have the same form at both higher and lower levels,differing only in scale.This focus on recursion is the reason for LISP's popularity with AI researchers, who often attempt to modellarge-scale behaviour in terms of smaller-scale decisions. For instance, recursion is often used in LISP tosearch state spaces.Many of the lists used in LISP programs would be better referred to as trees. Lists are simply the mechanismused to represent those trees.The car and cdr functions are generally used to recurse (or 'walk') through the elements in a tree, while cons is often used to gradually build build tree structures to form the result of a recursive operation. By alsousing the null function to test for an empty list, we can walk through the tree structure, dealing withsuccessively smaller pieces of the tree. car returns the first element of a list. e.g. ( car '(a b c) ) evaluates to a. cdr returns the list with the first element removed. e.g. ( cdr '(a b c) ) evaluates to (b c).

cons is an associated function which is used to build tree structures, often to form the result of a recursiveoperation. Note that it does not simply concatenate lists, but undoes the effects of a hypothetical use of car and cdr . e.g. ( cons '(a b) '(c d e) ) evaluates to ( (a b) (c d e)) rather than (a b c d e). Note that the use of these functions can lead to a great deal of inefficient copying As Im not handling this subject, I cant guarantee the accuracy of every answer--- Read on your own risk!!!Solved by SURESH the SUN , lecturer at BCA dept, SG College Campus --- Koppal pg. no: 29 1. As Im not handling this subject, I cant guarantee the accuracy of every answer--- Read on your own risk!!!Solved by SURESH the SUN , lecturer at BCA dept, SG College Campus --- Koppal pg. no: 30 1. A IT IS USEFUL TO STRUCTURE AI. PRODUCTION SYSTEMPROVIDES SUCH STRUCTURE? DISCUSS IN DETAIL A production system is a tool used in artificial intelligence and especially within the applied AIdomain known as expert systems. Production systems consist of a database of rules, a workingmemory, a matcher, and a procedure that resolves conflicts between rules. These components areoutlined below. Several different versions of productions systems have been developed,including the OPs series Matching The rules of a production consist of a condition and action in the form: ( if x then y ). The left-hand-sideconditions ( x and y may be arbitrarily complex conjunctions of expressions) are compared against theelements of working memory to determine if the conditions are satisfied. Matching is an computationallyintense procedure although the RETE algorithm of OPS5 is significantly more efficient than a simplecondition-by-condition matcher. Conflict Resolution At any point in processing, several productions may match to the elements of working memorysimultaneously. Since production systems are normally implemented on serial computers, this results in a conflict : there is a non-unique choice about which action to take next. Most conflict resolution schemes arevery simple, dependent on the number of conditions in the production, the time stamps (ages) of theelements to which the conditions matched, or completely random. One of the advantages of productionsystems is that the computational complexity of the matcher, while large, is deterministically finite and theconflict resolution scheme is trivial. This is in contrast to logicist systems in which declarative knowledgemay be accessed instantly but the time required to use the knowledge (in a theorem prover, for instance) cannot be pre-determined. Actions

The subsymbolic form of some commonsense knowledgeMuch of what people know is not represented as "facts" or "statements" that they could expressverbally. For example, a chess master will avoid a particular chess position because it "feels tooexposed" [53] or an art critic can take one look at a statue and instantly realize that it is a fake. [54] These are intuitions or tendencies that are represented in the brain non-consciously and sub-symbolically. [55] Knowledge like this informs, supports and provides a context for symbolic,conscious knowledge. As with the related problem of sub-symbolic reasoning, it is hoped thatsituated AI or computational intelligence will provide ways to represent this kind of knowledge. [55] Planning A hierarchical control system is a form of control system in which a set of devices and governing softwareis arranged in a hierarchy. As Im not handling this subject, I cant guarantee the accuracy of every answer--- Read on your own risk!!!Solved by SURESH the SUN , lecturer at BCA dept, SG College Campus --- Koppal pg. no: 34Main article: Automated planning and schedulingIntelligent agents must be able to set goals and achieve them. [56] They need a way to visualize the future(they must have a representation of the state of the world and be able to make predictions about how their actions will change it) and be able to make choices that maximize the utility (or "value") of the availablechoices. [57] In classical planning problems, the agent can assume that it is the only thing acting on the world and it can be certain what the consequences of its actions may be. [58] However, if this is not true, it must periodicallycheck if the world matches its predictions and it must change its plan as this becomes necessary, requiringthe agent to reason under uncertainty. [59] Multi-agent planning uses the cooperation and competition of many agents to achieve a given goal.Emergent behavior such as this is used by evolutionary algorithms and swarm intelligence. [60] Learning Main article: Machine learningMachine learning [61] has been central to AI research from the beginning. [62] In 1956, at the originalDartmouth AI summer conference, Ray Solomonoff wrote a report on unsupervised probabilistic machinelearning: "An Inductive Inference Machine". [63] Unsupervised learning is the ability to find patterns in astream of input. Supervised learning includes both classification and numerical regression. Classification isused to determine what category something belongs in, after seeing a number of examples of things fromseveral categories. Regression takes a set of numerical input/output examples and attempts to discover acontinuous function that would generate the outputs from the inputs. In reinforcement learning [64] the agentis rewarded for good responses and punished for bad ones. These can be analyzed in terms of decisiontheory, using concepts like utility. The mathematical analysis of machine learning algorithms and their performance is a branch of theoretical computer science known as computational learning theory.

[65] Natural language processing A parse tree represents the syntactic structure of a sentence according to some formal grammar.Main article: Natural language processing Natural language processing [66] gives machines the ability to read and understand the languages that humansspeak. Many researchers hope that a sufficiently powerful natural language processing system would be able As Im not handling this subject, I cant guarantee the accuracy of every answer--- Read on your own risk!!!Solved by SURESH the SUN , lecturer at BCA dept, SG College Campus --- Koppal pg. no: 35to acquire knowledge on its own, by reading the existing text available over the internet. Somestraightforward applications of natural language processing include information retrieval (or text mining)and machine translation. [67] Motion and manipulation Main article: RoboticsThe field of robotics [68] is closely related to AI. Intelligence is required for robots to be able to handle suchtasks as object manipulation [69] and navigation, with sub-problems of localization (knowing where you are),mapping (learning what is around you) and motion planning (figuring out how to get there). [70] Perception Main articles: Machine perception, Computer vision, and Speech recognitionMachine perception [71] is the ability to use input from sensors (such as cameras, microphones, sonar andothers more exotic) to deduce aspects of the world. Computer vision [72] is the ability to analyze visual input.A few selected subproblems are speech recognition, [73] facial recognition and object recognition. [74] Social intelligence Main article: Affective computingKismet, a robot with rudimentary social skillsEmotion and social skills [75] play two roles for an intelligent agent. First, it must be able to predict theactions of others, by understanding their motives and emotional states. (This involves elements of gametheory, decision theory, as well as the ability to model human emotions and the perceptual skills to detectemotions.) Also, for good human-computer interaction, an intelligent machine also needs to display emotions. At the very least it must appear polite and sensitive to the humans it interacts with. At best, itshould have normal emotions itself. Creativity Main article: Computational creativityA sub-field of AI addresses creativity both theoretically (from a philosophical and psychological perspective) and practically (via specific implementations of systems that generate outputs that can beconsidered creative, or systems that identify and assess creativity). A related area of computational researchis Artificial Intuition and Artificial Imagination. [ citation needed ]

, lecturer at BCA dept, SG College Campus --- Koppal pg. no: 37 No person could ever supply a complete set of such rules. No program could easily handle all those rules. Just storing so many rules poses seriousdifficulties.Defining chess problem as State Space search We need to write the rules describing the legal moves in as general a way as possible. For example: White pawn at Square( file e, rank 2) AND Square( File e, rank 3) is empty AND Square(filee, rank 4) is empty, then move the pawn from Square( file e, rank 2) to Square( file e, rank 4). In general, the more succintly we can describe the rules we need, the less work we will have to do to provide them and more efficient the program.Water Jug Problem The state space for this problem can be described as the set of ordered pairs of integers (x,y) suchthat x = 0, 1,2, 3 or 4 and y = 0,1,2 or 3; x represents the number of gallons of water in the 4-gallon jug and y represents the quantity of water in 3-gallon jug The start state is (0,0) The goal state is (2,n)Production rules for Water Jug ProblemSl No Current state Next State Descritpion1 (x,y) if x < 4 (4,y) Fill the 4 gallon jug2 (x,y) if y <3 (x,3) Fill the 3 gallon jug3 (x,y) if x > 0 (x-d, y) Pour some water out of the 4 gallonug4 (x,y) if y > 0 (x, y-d) Pour some water out of the 3-gallonug5 (x,y) if x>0 (0, y) Empty the 4 gallonug6 (x,y) if y >0 (x,0) Empty the 3 gallonug on the ground7 (x,y) if x+y >= 4and y >0(4, y-(4-x)) Pour water fromthe 3 gallon juginto the 4 gallonug until the 4-gallon jug is full As Im not handling this subject, I cant guarantee the accuracy of every answer--- Read on your own risk!!!Solved by SURESH the SUN , lecturer at BCA dept, SG College Campus --- Koppal pg. no: 38Production rules8 (x, y) if x+y >= 3and x>0(x-(3-y), 3) Pour water from the 4-gallon jug into the 3-gallon jug until the 3-gallon jug is full9 (x, y) if x+y <=4 andy>0(x+y, 0) Pour all the water from the 3-gallon juginto the 4-gallon jug10 (x, y) if x+y <= 3and x>0(0, x+y) Pour all the water from the 4-gallon juginto the 3-gallon jug11 (0,2) (2,0) Pour the 2 gallonsfrom 3-gallon jug intothe 4-gallon jug12 (2,y) (0,y) Empty the 2 gallons inthe 4-gallon jug on thegroundTo solve the water jug problem Required a control structure that loops through a simple cycle in which some rule whose left sidematches the current state is chosen, the appropriate change to the state is made as described in thecorresponding right side, and the resulting state is checked to see if it corresponds to goal state. One solution to the water jug problem Shortest such sequence will have a impact on the choice of appropriate mechanism to guide thesearch for solution.Gallonsin the4-gallonugGallonsin the3-gallonugRule applied0 0 20 3 93 0 23 3 74 2 5 or 120 2 9

As Im not handling this subject, I cant guarantee the accuracy of every answer--- Read on your own risk!!!Solved by SURESH the SUN , lecturer at BCA dept, SG College Campus --- Koppal pg. no: 39 2.B DIFFERENTIATE BETWEEN DEPTH FIRST VERSUSBREADTH FIRST SEARCH METHOD Breadth-first search (BFS) and depth-first search (DFS) are two distinct orders in which to visit the verticesand edges of a graph. BFS radiates out from a root to visit vertices in order of their distance from the root.Thus closer nodes get visited first.DFS prefers to visit undiscovered vertices immediately, so the search trees tend to be deeper rather than balanced as with BFS. Notice that the DFS consists of three

``Hamiltonian'' paths, one in each component --while the BFS tree has far more degree-3 nodes, reflecting balance. As Im not handling this subject, I cant guarantee the accuracy of every answer--- Read on your own risk!!!Solved by SURESH the SUN , lecturer at BCA dept, SG College Campus --- Koppal pg. no: 40 3. 3.A WHAT IS HEURISTICS? EXPLAIN ANY HEURISTIC SEARCHMETHOD A branch of artificial intelligence, which uses heuristics -- common-sense rules drawn from experience -- tosolve problems. This is in contrast to algorithmic programming, which is based on mathematically provable procedures. Heuristic programming is characterized by programs that are self-learning; they get better withexperience. Heuristic programs do not always reach the very best result but usually produce a good result.Many expert systems use heuristic programming. A heuristic is a method that might not always find the best solution but is guaranteed to find a good solution in reasonable time. By sacrificing completeness it increases efficiency. Useful in solving tough problems which o could not be solved any other way. o solutions take an infinite time or very long time to compute. Heuristic Search methods Generate and Test Algorithm 1. generate a possible solution which can either be a point in the problem space or a path from theinitial state.2. test to see if this possible solution is a real solution by comparing the state reached with the set of goal states.3. if it is a real solution, return. Otherwise repeat from 1.This method is basically a depth first search as complete solutions must be created before testing. It is oftencalled the British Museum method as it is like looking for an exhibit at random. A heuristic is needed tosharpen up the search. Consider the problem of four 6-sided cubes, and each side of the cube is painted inone of four colours. The four cubes are placed next to one another and the problem lies in arranging them sothat the four available colours are displayed whichever way the 4 cubes are viewed. The problem can only be solved if there are at least four sides coloured in each colour and the number of options tested can bereduced using heuristics if the most popular colour is hidden by the adjacent cube. The classic example of heuristic search methods is the travelling salesman problem. The travelling salesman problem

visiting all 24,978 towns in Sweden was solved: a tour of length approximately 72,500 kilometers was found and it was proven that no shorter tour exists. ( All thecities in Sweden can be covered within a network distance of 72500 Kms) 3.B DEFINE MATCHING. EXPLAIN ANY ONE MATCHING TECHNIQUE matching: In a biometric security system, the process of comparing a biometric sample with a storedreference template and subsequently assigning a score based on the level of similarity. The biometric systemthen issues an accept or reject decision based on the results of the matching.In its most general form a pervasive feature of, or basis for, AI systems: the essential objective isto test whether a specific received data structure is an instance of a given general pattern, and particularly, to establish whether input data items can provide values for pattern variables. Thematching can be made more or less fuzzy, according to the conditions on the individual patternvariables, and on their joint satisfaction. Pattern matching is important in AI because it reflects(i) the fact that complex general concepts exhibit considerable variation in particular manifestations, and (ii) the fact that individual elements of these participate in relationships withone another As Im not handling this subject, I cant guarantee the accuracy of every answer--- Read on your own risk!!!Solved by SURESH the SUN , lecturer at BCA dept, SG College Campus --- Koppal pg. no: 43 4. 4.A HOW DO YOU REPRESENT THE KNOWLEDGE USINGPREDICATE LOGIC One of the trickier parts of designing artificial intelligence is how to represent information to something thatcan not understand language. Knowledge representation is defined by its syntax and its facts (semantics)which together along with the rules for deducing new sentences make up the logic. Entailment is therelationship between current sentences and new sentences derived from the current sentences. A goodknowledge representation language will combine the ease of spoken and written languages, like English,with the conciseness of a computer language, like C.Propositional (Boolean) Logic This consists of a syntax, the semantics and rules for deducing newsentences. Symbols are used to represent facts which may or may not be true. W may 72 represent the fact itis windy outside. The symbols are combined with boolean logic to generate new sentences. Facts can be trueor false only. The program may know a statement is true or false or be uncertain as to its truth or falsity. Thesyntax consists of , v, => (if x then y), (equal), and (not). Backus-Naur Form (bnf) is the grammar used to put sentences together. The semantics are just the interpretation of a statement about a proposition. Truthtables are used to define the semantics of sentences or test validity of statements.Truth table for ANDT and T = TT and F = FF and F = FF and T = FA model is a world in which a sentence is true under a particular interpreta tion. There can be severalmodels at once that have the same interpretations. An inference rule is a rule that is derived from a patternthat is true all the time for specific cases. As Im not handling this subject, I cant guarantee the accuracy of every answer--- Read on your own risk!!!Solved by SURESH the SUN , lecturer at BCA dept, SG College Campus --- Koppal pg. no: 44First Order Logic (first-order predicate calculus)This consists of objects, predicates on objects, connectives and quantifiers. Predicates are the relations between objects, or properties of the objects. Connectives and quantifiers allow for universal sentences.Relations between objects can be true or false as well as the objects themselves. The program may not knowwhether something is true or false or give it a probability of truth or falseness.Procedural RepresentationThis method of knowledge representation encodes facts along with the sequence of operations for manipulation and processing of the facts. This is what expert systems are based on. Knowledge engineersquestion experts in a given field and code this information into a computer program.

In propsoitional logic it is easy to determine that two literals can not both be true at the same time. Simplylook for L and ~L . In predicate logic, this matching process is more complicated, since bindings of variables must be considered.For example man (john) and man(john) is a contradiction while man (john) and man(Himalayas) is not.Thus in order to determine contradictions we need a matching procedure that compares two literals anddiscovers whether there exist a set of substitutions that makes them identical . There is a recursive procedurethat does this matching . It is called Unification algorithm.In Unification algorithm each literal is represented as a list, where first element is the name of a predicateand the remaining elements are arguments. The argument may be a single element (atom) or may be another list. For example we can have literals as( tryassassinate Marcus Caesar)( tryassassinate Marcus (ruler of Rome))To unify two literals , first check if their first elements re same. If so proceed. Otherwise they can not beunified. For example the literals( try assassinate Marcus Caesar)( hate Marcus Caesar)Can not be Unfied. The unification algorithm recursively matches pairs of elements, one pair at a time. Thematching rules are : As Im not handling this subject, I cant guarantee the accuracy of every answer--- Read on your own risk!!!Solved by SURESH the SUN , lecturer at BCA dept, SG College Campus --- Koppal pg. no: 48i) Different constants , functions or predicates can not match, whereas identical ones can.ii) A variable can match another variable , any constant or a function or predicate expression, subject to thecondition that the function or [predicate expression must not contain any instance of the variable beingmatched (otherwise it will lead to infinite recursion).iii) The substitution must be consistent. Substituting y for x now and then z for x later is inconsistent. (asubstitution y for x written as y/x)The Unification algorithm is listed below as a procedure UNIFY (L1, L2). It returns a list representing thecomposition of the substitutions that were performed during the match. An empty list NIL indicates that amatch was found without any substitutions. If the list contains a single value F, it indicates that theunification procedure failed.UNIFY (L1, L2)1. if L1 or L2 is an atom part of same thing do(a) if L1 or L2 are identical then return NIL(b) else if L1 is a variable then do(i) if L1 occurs in L2 then return F else return (L2/L1) else if L2 is a variable then do(i) if L2 occurs in L1 then return F else return (L1/L2)else return F.2. If length (L!) is not equal to length (L2) then return F.3. Set SUBST to NIL( at the end of this procedure , SUBST will contain all the substitutions used to unify L1 and L2).4. For I = 1 to number of elements in L1 doi) call UNIFY with the i th element of L1 and Ith element of L2, putting the result in Sii) if S = F then return Fiii) if S is not equal to NIL then do(A) apply S to the remainder of both L1 and L2(B) SUBST := APPEND (S, SUBST) return SUBST. As Im not handling this subject, I cant guarantee the accuracy of every answer--- Read on your own risk!!!Solved by SURESH the SUN , lecturer at BCA dept, SG College Campus --- Koppal pg. no: 49 5. 5.A DEFINE PREDICATE AN OBJECTS IN PROLOG. DISCUSSVARIOUS TYPES OF OBJECTS USED IN PROLOG Predicates Clauses with the same clause name, the same number of arguments and defined in the same module arecombined in the database and form the definition of a predicate .The common clause name is called the predicate name or function of the predicate. The number of arguments is the parity . For example, the predicate fac/2 is defined by the collection of all clauses with theclause head fac(

Arg1,Arg2 ) , where Arg1 and Arg2 may be any terms.The separate clauses of a predicate are connected by disjunction, i.e. by inclusive OR.Clauses with the same clause name but a different number of arguments belong to different predicates.Likewise, clauses which have the same clause name and the same arity but are associated with differentmodules belong to different predicates.The Prolog predicate concept can be compared to the subprogram concept in conventional programminglanguages; we therefore also speak of "calling" a predicate in Prolog. The predicate concept ensures a highdegree of modularity in Prolog programs and thereby supports structured programming. Example The two clauses below define the predicate fac/2 for calculating the factorial of a natural number. fac( 0, 1) :- !. % 0! is 1fac( N, Nfac) :-N > 0, % for integers N > 0M is N - 1, % defines NFac as N * (N1)!fac( M, Mfac), % thus MFac is calculatedNfac is N * Mfac. % recursively as (N-1)! You can call the predicate fac/2 in the Prolog input loop by entering, for example, [user] ?fac(5,X). The Prolog system searches the clauses belonging to the predicate fac/2 and displays the answer: X = 120 The precise sequence in which Prolog performs this search operation is described in the section Procedureexecution .Only predicates whose clauses have been included in the database with consult/1 , reconsult/1 or with an assert predicate can be modified, i.e. clauses can be added ( assert predicates) or removed ( retract predicates), individual predicates can be deleted ( abolish/1 ) or replaced ( reconsult/1 ). The clauses of As Im not handling this subject, I cant guarantee the accuracy of every answer--- Read on your own risk!!!Solved by SURESH the SUN , lecturer at BCA dept, SG College Campus --- Koppal pg. no: 50these predicates can be output with listing/0/1 and analyzed with

clause predicates. Note however thatto do so you must call the Prolog system with the -debug option. Compiled predicates IF/Prolog offers a number of ways of compiling user-defined predicates and including them in thedatabase. This can be done by the system's incremental compiler by using the assert and consult predicates. In addition, predicate definitions stored in files can be compiled by the predicate compile/1 or the external compiler ( procmp command).Predicates compiled with consult/1 , reconsult/1 , compile/1 or procmp are normally no longer modifiable. However, you can inform the compiler with the dynamic/1 directive that certain predicates areto remain modifiable. Predicates which you have generated with assert predicates or which you havedeclared as modifiable with other compilation methods are compiled only to the extent where thecompilation is reversible, i.e. where decompilation is possible.Whenever references are made in this manual to compiled predicates they should be taken to mean predicates which cannot be decompiled. These can no longer be modified by simply adding or removingclauses. Further information about compiling Prolog source text and the related advantages and restrictionscan be found in chapter 7.5 on Compiling and loading files . C interface IF/Prolog also gives you the option of using C functions without backtracking (simple C functions) andwith backtracking (complex C functions) as Prolog predicates using the built-in C interface. The C interfaceis described in detail in chapter 10. Built-in predicates IF/Prolog provides a large number of built-in predicates which you can use to formulate your own predicates.Built-in predicates cannot be extended by additional clauses or entirely replaced. The module system does,however, give you the option to define your own predicates with the same clause names and the same arityas built-in predicates, since all the built-in predicates are defined in special system modules.An overview and an alphabetically arranged description of the built-in predicates can be found in the IF/Prolog Reference Manual [1].Predicates which permit backtracking are indicated by a hash character (' # ') in front of the functor. Thischaracter does not appear with predicates not having this capability.For metapredicates

, the argument list is followed by the text [ @ + Module ] . The module qualification can be specified by @/2 . Metapredicates are supplied with information on the calling module. As Im not handling this subject, I cant guarantee the accuracy of every answer--- Read on your own risk!!!Solved by SURESH the SUN , lecturer at BCA dept, SG College Campus --- Koppal pg. no: 51 Directives are special syntactic structures which can be specified in IF/Prolog texts and which are processedwhen these texts are read in (e.g. with consult/1 ). They are indicated by :in front of the functor, as theywould be written in a Prolog text. User definable predicates are automatically called at particular points by IF/Prolog if the user has definedthem. They are identified by the text [ :Body ] after the argument list.The call mode specifies the instantiation of an argument at the time of the call. In front of each argumentthere is a sign (' @ ', ' + ', ' ', or ' ? ') to indicate the call type of the argument, as follows: @ The argument is a pure input parameter. The current parameter specified in the call must be of the prescribed type and any uninstantiated variables contained in this parameter are not instantiated inthe call. + The argument is an input parameter. The current parameter specified in the call must be of the prescribed type. Any uninstantiated variables contained in this parameter may be instantiated in thecall.When the argument is an atomic term, there is no difference between the modes + and @ . The mode @

is therefore used only when the argument may be a compound term. ? The argument is an input/output parameter. The current parameter must be either a variable or aterm of the prescribed type. In the course of the execution of the predicate, this parameter is unified.If this unification is not successful, then the entire predicate call will fail. Any uninstantiatedvariables contained in this parameter may be instantiated in the call. The argument is a pure output parameter. The current parameter must be an uninstantiated variable.If the predicate succeeds, this variable is instantiated with the result of the predicate call. The type of result from the predicate call is indicated in the section on ' Arguments ' in the full description.Several call patterns are possible for some predicates.In some predicates where an integer is expected as an input parameter, it is also possible to input anarithmetic expression with an integer value; an expression will be evaluated implicitly as with is/2 . Examples If uninstantiated variables are permitted in the mode @ , they will not be instantiated.The argument of atom/1 has the call mode @ . It is therefore possible to specify a variable in order, for example, to test whether it is instantiated to an atom. This variable will not be instantiated, however.The three arguments of current_op/3 have the call mode ? . If all three arguments are uninstantiatedvariables, you can obtain all defined operators by means of backtracking: [user] ?current_op(Precedence,Type,Name). Precedence = 50 As Im not handling this subject, I cant guarantee the accuracy of every answer--- Read on your own risk!!!Solved by SURESH the SUN , lecturer at BCA dept, SG College Campus --- Koppal pg. no: 52 Type = xfxName = : ;Precedence = 100Type = xfxName = @ ; etc. until you terminate backtracking. The instantiated arguments are unified; the uninstantiated variables are instantiated. The following queriesoperators with precedence 400: [user] ?current_op(400,Type,Name). Type = yfxName = >> ;Type = yfxName = <<Yes 5.B WRITE A PROLOG PROGRAM TO GENERATE FIBONACCISERIES Prolog program to generate a fibonacci series of N elements domainsx = integerpredicatesfibonacci(x)clausesfibonacci(1).fibonacci(N) :-N1 = N - 1,N1 >= 0,!,fibonacci(N1),write(F1," ,"),F = F1 +

N.domainsnum,ans=integer.predicatesfibo(num).clausesfibo(1):-write("1").fibo(X):- X<5,!,fibo(X1 +1),Ans=X1+X. As Im not handling this subject, I cant guarantee the accuracy of every answer--- Read on your own risk!!!Solved by SURESH the SUN , lecturer at BCA dept, SG College Campus --- Koppal pg. no: 53 Top Down Computation Top down computation, typically used in Prolog, starts with the original problem and itdecomposes this problem to simpler and simpler problems till the trivial problem, i.e., the fact inProlog database, is reached. Then, the solution of larger problems is composed of the solutions of simpler problems etc. till the solution of the original problem is obtained. Following two examplespresent programs that use the top down computation. Fibonacci The following program computes Fibonacci numbers using the top down method, i.e., if we arelooking for Fibonacci number of N>1, we first compute Fibonacci numbers of N-1 and N-2 (usignthe same procedure) and, then, we compose the Fibonacci number of N from the subresults. Inthis case, the recursion stops as soon as the Fibonacci number of 0 or 1 is computed. fibo_td(0,0).fibo_td(1,1)fibo_td(N,F):-N>1, N1 is N-1, N2 is N-2,fibo_td(N1,F1), fibo_td(N2,F2),F is F1+F2. Note, that the above procedure is very inefficient if standard Prolog execution rule is usedbecause we compute the same thing many times. For example, to compute F(N-1) we need tocompute F(N-2) which is also required to compute F(N) that was decomposed to F(N-1) and F(N-2). In fact, the complexity of the above procedure is exponential thas is "not very efficient". Bottom Up Computation Even if the top down computation is typical for Prolog, we can still simulate the bottom upcomputation as well without changes of the Prolog interpreter. The bottom up computation startswith know facts and extends the set of know trues using rules. i.e., it derives new facts from oldfacts and rules. This extension continues till the solved problem is present in the computed set of facts. In general, pure bottom up method is less efficient than top down method because many facts arederived that has nothing in common with the original problem. Therefore, Prolog uses top downevaluation as a standard method of computation. However, in same cases, it is possible to guidethe bottom up evaluation towards the solution of the original problem. The following two examples present bottom up versions of the above two procedures for computing factorial and Fibonacci numbers. The advantage of bottom up evaluation is visiblemainly in the procedure fibo_bu that is a lot of faster than fibo_td. As Im not handling this subject, I cant guarantee the accuracy of every answer--- Read on your own risk!!!Solved by SURESH the SUN , lecturer at BCA dept, SG College Campus --- Koppal pg. no: 54 Fibonacci We can use the same principle as in "bottom-up factorial" to compute the Fibonacci numbersusing bottom up method. Now, we need to remember last two Fibonacci numbers to be able tocompute the next Fibonacci number. fibo_bu(N,F):-fibo_bu1(0,0,1,N,F).fibo_bu1(N,F,_,N,F)fibo_bu1(N1,F1,F2,N,F):-N1<N, N2 is N1+1, F3 is F1+F2,fibo_bu1(N2,F2,F3,N,F). Note, that the complexity of fibo_bu is linear and therefore the procedure fibo_bu is far awayefficient than fibo_td that is exponential. 6. 6.A EXPLAIN VARIOUS LIST PROCESSING FUNCTIONS OF LISP>>>>>>>>>REPEATED<<<<<<<<< 2007 Lists are powerful data structures for holding and manipulating groups of things. In Prolog, a list is simply acollection of terms. The terms can be any Prolog data types,including structures and other

:(DEFINE (RECITE (LAMBDA (STUFF): (COND ((NULL STUFF) ()): (T (PRINT (CAR STUFF)): (RECITE (CDR STUFF))): ))))RECITE:(RECITE '(THIS IS A TEST LIST))THISISATESTLISTNIL When STUFF is NIL, the COND evaluates "(null stuff)" to T and evaluates the "()" as dictated by COND.Otherwise it prints the CAR of the list and calls RECITE, binding the CDR of STUFF to the new STUFF. Notice that it does not replace the value of STUFF but simply binds a new local value to it. When that particular call terminates, the previous value of STUFF will return. The NIL displayed at the end is not printed by the PRINT function. Rather, it is the value returned by the RECITE function. It came from thesuccession of recursive function terminations. When the function we started off with terminates, it prints outits value because there is no "caller" to return to other than the user.What would have happened if we had left out the termination condition? Answer: no end in sight.

Significant Language Features Prolog is a rich collection of data structures in the language and human reasoning, and a powerful notationfor encoding end-user applications. It has its logical and declarative aspects, interpretive natur, compactness,and inherent modularity. Intelligent Systems - programs which perform useful tasks by utilizing artificaial intelligencetechniques. Expert Systems - intelligent systems which reproduce decision-making at the level of a humanexpert. Natural Language Systems - which can analys and respond to statements made in ordinarylanguage as opposed to approved keywords or menu selections. Relational Database Systems Areas of Application Prolog is the highest level general-purpose language widely used today. It is taught with a strong declarativeemphasis on thinking of the logical relations between objects or entities relevant to a given problem, rather than on procedural steps necessary to solve it. The system decides the way to solve the problem, includingthe sequences of instructions that the computer must go through to solve it. It is easier to say what we wantdone and leave it to the computer to do it for us. Since a major criterion in the commercial world today isspeed of performance, Prolog is an ideal prototyping language. Its concept makes use of parallelarchitectures. It solves problems by searching a knowledge base (or more correctly a database) which would be greatly improved if several processors are made to search different parts of the database. 8. WRITE A SHORT NOTES ONa. forward versus backward reasoning b. STRUCTURE OF PROLOG PROGRAM >>>>> REPEATED2007 c. CHARACTERISTICS OF KNOWLEDGE d. SYNTAX AND SEMANTICS OF PROPOSITIONAL LOGIC A. forward versus backward reasoning Whether you use forward or backwards reasoning to sove a problem depends on the properties of your rule set and initial facts. Sometimes, if you have some particular goal (to test somehypothesis), then backward chaining will be much more efficient, as you avoid drawingconclusions from irrelevant facts. However, sometimes backward chaining can be very wasteful -there may be many possible ways of trying to prove something, and you may have to try almostall of them before you find one that works. Forward chaining may be better if you have lots of things you want to prove (or if you just want to find out in general what new facts are true);when you have a small set of initial facts; and when there tend to be lots of different rules whichallow you to draw the same conclusion. Backward chaining may be better if you are trying to prove a single fact, given a large set of initial facts, and where, if you used forward chaining, lotsof rules would be eligible to fire in any cycle.The state space representation forms the basis of most of the AI methods.Its structure corresponds to the structure of problem solving in two important ways: As Im not handling this subject, I cant guarantee the accuracy of every answer--- Read on your own risk!!!Solved by SURESH the SUN , lecturer at BCA dept, SG College Campus --- Koppal pg. no: 65It allows for a formal definition of a problem as the need to convert some given situation intosome desired situation using a set of permissible operations.It permits us to define the process of solving a particular problem as a combination of knowntechniques (each represented as a rule defining a single step in the space) and search, the generaltechnique of exploring the space to try to find some path from current state to a goal state.Search

is a very important process in the solution of hard problems for which no more directtechniques are available. Forward chaining means applying rules in a forward direction: recursively applying the rules over datato generate more data (and applying the rules over that data... I have a member of po:Person ... it must also be a member of foaf:Person ... and so it must be a foaf:Agent and dc:Agent ... and so...) Backward chaining means applying rules in a backwards manner: taking a goal (e.g., a query) andrecursively working backwards to find more data that can satisfy the goal (I'm looking for foaf:Agent s... Ishould also look for dc:Agent s and foaf:Person s and po:Person s...) forward-chaining (~materialisation): precomputing and storing answers is suitable for: o frequently accessed data, o which are relatively static, o which are expensive to compute, and/or o which are small enough to efficiently store o (a la Lesson 6) backward-chaining (~query-rewriting): storing a minimal index from which answers can be computed on demand is more suitable where: o there is little scope for reuse of computed answers, o the answers are dynamic, o answers can be efficiently computed at runtime, and/or

o the "answer space" is too large to materialise and storeA hybrid approach should then give the best of both worlds, materialising the inferences that are frequentlyaccessed, static, and/or small, and supporting query-rewriting for inferences that are large, cheap to do atruntime, dynamic and/or infrequently accessed.For example, many large-scale reasoners: typically rely on materialisation to do the bulk of reasoning. use backward-chaining to support stuff like reflexive owl:sameAs statements, or rdf:typerdfs:Resource/owl:Thing use a hybrid approach for equality (to avoid ~quadratic materialisation: a maximum of n inferenceswhere n is the no. of input triples), where o each set of "URI aliases" (identifiers related by owl:sameAs ) is stored in a special index o one URI is chosen as a canonical identifier to represent all such aliases in the indexed data o queries are rewritten to use the chosen canonical identifer o results data can be (optionally as needed) expanded to use all combinations of identifiers. B.. STRUCTURE OF PROLOG PROGRAM >>>>> REPEATED 2007 As Im not handling this subject, I cant guarantee the accuracy of every answer--- Read on your own risk!!!Solved by SURESH the SUN , lecturer at BCA dept, SG College Campus --- Koppal pg. no: 66 C.CHARACTERISTICS OF KNOWLEDGE A good knowledge representation covers six basic characteristics: Coverage, which means the KR covers a breath and depth of information. Without a wide coverage,the KR cannot determine anything or resolve ambiguities. Understandable by humans. KR is viewed as a natural language, so the logic should flow freely. Itshould support modularity and hierarchies of classes (Polar bears are bears, which are animals). Itshould also have simple primitives that combine in complex forms. Consistency. If John closed the door, it can also be interpreted as the door was closed by John. By being consistent, the KR can eliminate redundant or conflicting knowledge. Efficient Easiness for modifying and updating.

Supports the intelligent activity which uses the knowledge baseTo gain a better understanding of why these characteristics represent a good knowledge representation,think about how an encyclopedia (e.g. Wikipedia) is structured. There are millions of articles (coverage),and they are sorted into categories, content types, and similar topics (understandable). It redirects differenttitles but same content to the same article (consistency). It is efficient, easy to add new pages or updateexisting ones, and allows users on their mobile phones and desktops to view its knowledge base. D. SYNTAX AND SEMANTICS OF PROPOSITIONAL LOGIC Syntax of Propositional Logic Logic is used to represent properties of objects in the world about which we are going to reason. When wesay Miss Piggy is plump we are talking about the object Miss Piggy and a property plump. Similarly whenwe say Kermit's voice is high-pitched then the object is Kermit's voice and the property is high-pitched. It isnormal to write these in logic as: plump(misspiggy) highpitched(voiceof(kermit)) So misspiggy and kermit are constants representing objects in our domain. Notice that plump and highpitched is different from voiceof : plump and highpitched are represent properties and so are boolean valued functions. They areoften called predicates or relations. voiceof is a function that returns an object (not true/false). To help us differentiate we shall use``of'' at the end of a function name.The predicates plump and highpitched are unary predicates but of course we can have binary or n-ary predicates; e.g. loves(misspiggy, voiceof(kermit)) As Im not handling this subject, I cant guarantee the accuracy of every answer--- Read on your own risk!!!Solved by SURESH the SUN , lecturer at BCA dept, SG College Campus --- Koppal pg. no: 67 Simple Sentences The fundamental components of logic are object constants; e.g. misspiggy, kermit

function constants; e.g. voiceof predicate constants; e.g. plump, highpitched, loved Predicate and function constants take arguments which are objects in our domain. Predicate constants areused to describe relationships concerning the objects and return the value true/false . Function constantsreturn values that are objects . Atom : An atom is a basic building block of logic consisting of a predicate constant applied to a set of objectsProlog programs and Clips rules also contain knowledge organised in this way: Prolog terms: loves(misspiggy, kermit) Clips ordered terms: (loves misspiggy kermit) Remember that in Clips ordered terms the first argument is special. It is common to represent knowledge intriples like this and so they have a name OAV (Object-Attribute-Value) triples where the attribute is predicate and the object and value are the arguments. More Complex Sentences We need to apply operators to construct more complex sentences from atoms. Negation: applied to an atom negates the atom: loves(kermit, voiceof(misspiggy)) ''Kermit does not love Miss Piggy's voice'' Conjunction: combines two conjuncts: loves(misspiggy, kermit) loves(misspiggy, voiceof(kermit)) ''Miss Piggy loves Kermit and Miss Piggy loves Kernit's voice'' Notice it is not correct syntax to write in logic loves(misspiggy, kermit) voiceof(kermit) As Im not handling this subject, I cant guarantee the accuracy of every answer--- Read on your own risk!!!Solved by SURESH the SUN , lecturer at BCA dept, SG College Campus --- Koppal pg. no: 68 because we have tried to conjoin a sentence (truth valued) with an object. Logic operators mustapply to truth-valued sentences. Disjunction: combines two disjuncts: loves(misspiggy, kermit) loves(misspiggy, voiceof(kermit)) ''Miss Piggy loves Kermit or Miss Piggy loves Kermit's voice'' Implication: combines a condition and conclusion loves(misspiggy, voiceof(kermit)) loves(misspiggy, kermit) ''If Miss Piggy loves Kermit's voice then Miss Piggy loves Kermit''

The language we have described so far contains atoms and the connectives , , and . This definesthe syntax of propositional Logic. It is normal to represent atoms in propositional logic as single upper-caseletters but here we have used a more meaningful terminology for the atoms that extends easily to PredicateLogic. Semantics of Propositional Logic We have defined the syntax of propositional Logic. However, this is of no use without talking about themeaning, or semantics, of the sentences. Suppose our logic contained only atoms; e.g. no logicalconnectives. This logic is very silly because any subset of these atoms is consistent; e.g. beautiful(misspiggy) and ugly(misspiggy) are consistent because we cannot represent ugly(misspiggy) beautiful(misspiggy) So we now need a way in our logic to define whichsentences are true. Model : A model is a subjet of the atoms defined for our language and contains exactly those atoms that aretrue. So all atoms in a model M are true and all atoms not in M are false Example: Models Define Truth Suppose a language contains only one object constant misspiggy and two relation constants ugly and beautiful . The following models define different facts about Miss Piggy. M=: In this model Miss Piggy is neither ugly nor beautiful. M={ ugly(misspiggy) }: In this model Miss Piggy is ugly and not beautiful. M={ beautiful(misspiggy) }: In this model Miss Piggy is beautiful and not ugly. M={ ugly(misspiggy), beautiful(misspiggy) }: In this model Miss Piggy is both ugly and beautiful. The last statement is intuitively wrong but the model selected commits the truth of theatoms in the language. As Im not handling this subject, I cant guarantee the accuracy of every answer--- Read on your own risk!!!Solved by SURESH the SUN , lecturer at BCA dept, SG College Campus --- Koppal pg. no: 69 Compound Sentences So far we have restricted our attention to the semantics of atoms: an atom is true if it is a member of themodel M; otherwise it is false. Extending the semantics to compound sentences is easy. Notice that in thedefinitions below and do not need to be atoms because these definitions work recursively until atomsare reached.

Conjunction: is true in M iff and are true in M individually.So the conjunct loves(misspiggy, kermit) loves(misspiggy, voiceof(kermit)) is true only when both Miss Piggy loves Kermit; and Miss Piggy loves Kermit's voice Disjunction: is true in M iff at least one of or is true in M.So the disjunct loves(misspiggy, kermit) loves(misspiggy, voiceof(kermit)) is true whenever Miss Piggy loves Kermit; Miss Piggy loves Kermit's voice; or Miss Piggy loves both Kermit and his voice.Therefore the disjunction is weaker than either disjunct and the conjunction of these disjuncts. Negation: is true in M iff is not true in M. Implication: is true in M iff is not true in M or is true in M.We have been careful about the definition of . When people use an implication they normallyimply that causes . So if is true we are happy to say that is true iff is true. But if is false thecausal link causes confusion because we can't tell whether should be true or not. Logic requires that theconnectives are truth functional and so the truth of the compound sentence must be determined from thetruth of its component parts. Logic defines that if is false then is true regardless of the truth of . As Im not handling this subject, I cant guarantee the accuracy of every answer--- Read on your own risk!!!Solved by SURESH the SUN , lecturer at BCA dept, SG College Campus --- Koppal pg. no: 70So both of the following implications are true (provided you believe pigs do not fly!): fly(pigs) beautiful(misspiggy) fly(pigs) beautiful(misspiggy) Example: Implications and Models In which of the following models is ugly(misspiggy) beautiful(misspiggy) true? M= Miss Piggy is not ugly and so the antecedent fails. Therefore the implication holds. (Miss Piggy isalso not beautiful in this model.) M={ beautiful(misspiggy) } Again, Miss Piggy is not ugly and so the implication holds. M={ ugly(misspiggy)