1 / Types and Programming Languages

Size: px
Start display at page:

Download "1 / Types and Programming Languages"

Transcription

1 1 / Types and Programming Languages

2 2 / 65 Outline Control Flow During Execution Tree Traversal A Detailed Trace Search Space Analysis Modelling Equations and Operations Lists

3 3 / 65 Outline Control Flow During Execution Tree Traversal A Detailed Trace Search Space Analysis Modelling Equations and Operations Lists

4 4 / 65 Aside: Depth-first Traversal Recall that the values contained in the leaf nodes of a complete ordered binary tree can be printed in order by the following algorithm: Definition in_order( tree(value,left,right) ) = { if is_leaf(tree(value,left,right)) then print(value) else { in_order(left); in_order(right) } }

5 5 / 65 Continued... Similarly, the leaves of an unordered complete binary tree can be searched for a particular value by the following algorithm: Definition search( tree, my_value) = { if isnull(tree) then return; // not found else if tree.value = my_value then { print(value); HALT; } else { search(tree.left,my_value); search(tree.right,my_value); } }

6 6 / 65 Relevance to Prolog Prolog uses a depth-first backtracking algorithm in order to search for solutions to queries. In this framework, a node in a tree corresponds to the goal that is currently under consideration, and its children are determined by the clauses in the program (considered in order) that can resolve against this goal.

7 7 / 65 Example F1: edge(v1, v2). F2: edge(v1, v3). F3: edge(v2, v3). F4: edge(v2, v4). R1: can_reach(x, X). R2: can_reach(x,z) :- edge(x,y), can_reach(y,z). Question: What will Prolog output in response to the following query??- can_reach( v1, X ), write(x), fail.

8 8 / 65 A Trace of:?- can_reach( v1, X ), write(x), fail. Step 0: Create Goal List - In this step, Prolog forms the query into a goal list. Here the (initial) goal list is: [can_reach( v1, X ), write(x), fail] Step 1: Goal Selection - In this step, Prolog selects the first goal from the goal list. That is, the goal can_reach(v1, X) is selected. If the goal list is empty, then halt. We will represent the selection of the first goal g1 in a list of goals as follows: [g1 g2, g3, g4,... ]

9 9 / 65 A Trace of:?- can_reach( v1, X ), write(x), fail. Step 2: Clause Selection - Prolog selects a candidate clause from the Prolog program that it will attempt to resolve against can_reach(v1, X). In this case, the first clause selected is the fact can_reach(x, X). Step 3: Variable Renaming - Prolog will rename the variables in the selected clause to ensure that the unique namespace property is preserved. For example, after renaming, the selected clause might be can_reach(x 100, X 100). Step 4: Unification - Next Prolog attempts to unify the clause with the goal. In this case, the clause and goal unify under the substitution σ = [X := v1, X100 := v1]. This substitution is now applied to: (1) the entire goal list as well as the currently selected goal, and (2) the entire selected clause.

10 10 / 65 A Trace of:?- can_reach( v1, X ), write(x), fail. Step 5: Deductive Step - Prolog now performs a deductive step by applying the resolution rule to the goal and clause. In this case the resulting clause is the empty clause. In the general case, the resulting clause is placed on the front of the goal list and the algorithm jumps to step 1. Placing the empty clause on the front of the goal list yields: [write(v 1), fail] Step 6: The next goal selected is write(v1). By definition, this goal succeeds and outputs the value v1.

11 11 / 65 A Trace of:?- can_reach( v1, X ), write(x), fail. Step 7: Next, the fail goal is processed. Again, by definition, this goal fails, and this failure causes Prolog to back up in its search for a solution to the query. Prolog uses a standard depth-first backtracking algorithm when searching for alternate solution candidates. First, Prolog will check to see if the write(v1) goal could have been satisfied in an alternate manner (i.e., by resolving with a different clause). After checking this, Prolog will back up further and check to see if the can_reach(v1, X) goal could have been satisfied differently. This causes Prolog to select the rule R2. Step 8: Clause Selection - Prolog selects the clause R2 as a candidate for resolution.

12 12 / 65 A Trace of:?- can_reach( v1, X ), write(x), fail. Step 9: Variable Renaming - The variables in R2 are renamed: can_reach(x101,z101) :- edge(x101,y101), can_reach(y101,z101). Step 10: Unification - Next Prolog attempts to unify the clause with the goal. In this case, the clause and goal unify under the substitution σ = [X101 := v1, Z 101 := X]. This substitution is now applied to: (1) the entire goal list as well as the currently selected goal, and (2) the entire selected clause. Thus we now have: Goal List: [can_reach(v 1, X) write(x), fail] Clause: can_reach(v1,x) :- edge(v1,y101), can_reach(y101,x).

13 13 / 65 A Trace of:?- can_reach( v1, X ), write(x), fail. Step 11: Deductive Step - Prolog now performs a deductive step by applying the resolution rule to the goal and clause. In this case the resulting clause is edge(v1, Y 101), can_reach(y 101, X) This result is placed on the front of the goal list. The new goal list is now: [edge(v1, Y 101), can_reach(y 101, X), write(x), fail] Step 12: Goal Selection - [edge(v 1, Y 101) can_reach(y 101, X), write(x), fail] Step 13: Clause Selection - The fact F1 is selected. Step 14: Variable Renaming - There are no variables to be renamed in F1.

14 14 / 65 A Trace of:?- can_reach( v1, X ), write(x), fail. Step 15: Unification - Under the substitution σ = [Y 101 := v2] the current goal edge(v1, Y 101) will unify with the fact edge(v1, v2). This substitution is now applied to the goal list yielding: [edge(v1, v2) can_reach(v2, X), write(x), fail] Step 16: Deductive Step - Prolog now performs a deductive step by applying the resolution rule to the goal and clause. In this case the resulting clause is the empty clause. Thus the goal list shrinks to: [can_reach(v 2, X), write(x), fail] Step 17: Goal Selection - [can_reach(v 2, X) write(x), fail]

15 15 / 65 A Trace of:?- can_reach( v1, X ), write(x), fail. Step 18: Clause Selection - The rule R1 is selected. Step 19: Variable Renaming - The variables are renamed yielding can_reach(x 102, X 102). Step 20: Unification - Under the substitution σ = [X := v2, X102 := v2] the current goal can_reach(v2, X) will unify with the fact can_reach(x 102, X 102). This substitution is now applied to the goal list yielding [can_reach(v 2, v 2) write(v 2), fail]. Step 21: Deductive Step - Prolog now performs a deductive step yielding: [write(v 2), fail]

16 A Trace of:?- can_reach( v1, X ), write(x), fail. As usual, the write goal will succeed causing v2 to be output.then the fail goal will fail causing Prolog to backtrack. We now have two very interesting questions: Question1 : Where does Prolog backtrack to? Question2 : Which is the next clause selected? Answer1 : Prolog will back-up to the previous goal list. The goal list that existed prior to the last unification step. Goal List: [can_reach(v 2, X) write(x), fail] Answer2 : With respect to the clause selection in the previous pass, Prolog will continue where it left off searching for another clause which can be a candidate for resolution with the current goal. Thus the next clause selected will be: Clause: can_reach(x, Z ) : edge(x, Y ), can_reach(y, Z ). 16 / 65

17 17 / 65 A Trace of:?- can_reach( v1, X ), write(x), fail. Step 22: Variable Renaming - The variables in the selected clause are renamed yielding: can_reach(x103,x103) :- The current goal list is: edge(x103,y103), can_reach(y103,z103). [can_reach(v 2, X) write(x), fail] Step 23: Unification - Under the substitution σ = [X103 := v2, Z 103 := X] the current goal can_reach(v2, X) will unify with can_reach(x103, Z 103). This substitution is now applied to the goal list leaving it unchanged.

18 18 / 65 A Trace of:?- can_reach( v1, X ), write(x), fail. Step 24: Deductive Step - Prolog now performs a deductive step yielding: edge(v2, X), can_reach(y 103, X) This result is placed on the front of the goal list and the algorithm continues with a goal selection step, etc..

19 19 / 65 A Symbolic Summary of the Trace The program under consideration and a given query: edge(v1,v2). edge(v1,v3). edge(v2,v3). edge(v2,v4). can_reach(x, X). can_reach(x,z) :- edge(x,y), can_reach(y,z).?- can_reach( v1, X ), write(x), fail.

20 20 / 65 A Symbolic Summary of the Trace Search Space and Search Order v1 v1 v1 v2, v2 v2 v1 v2, v2 v3, v3 v3 v1 v2, v2 v3, v3? v1 v2, v2 v4, v4 v4 v1 v2, v2 v4, v4? v1 v2, v2? v1 v3, v3 v3 v1 v3, v3? v1? Output: v1 v2 v3 v4 v3

21 21 / 65 A Graphical Summary of the Trace V1 V1 V2 V3 V3? V2 V3 V4 V3 V4??

22 22 / 65 Discussion A query ending with the fail goal, will cause Prolog to exhaustively search the entire solution space of a program in an effort to satisfy the query. Such an exhaustive search will only terminate if the domain(s) being searched is finite. During an exhaustive search, multiple solutions to a query may be found. Such solutions may even result in the same variable bindings.

23 23 / 65 Continued... In the case of the graph reachability problem the solutions to can_reach(v1, X) can be satisfied as follows: v1 can reach v1 through zero edge traversals v1 can reach v2 via edge(v1, v2) v1 can reach v3 via edge(v1, v3) and edge(v2, v3) v1 can reach v4 via edge(v1, v2) and edge(v2, v4) v1 can reach v3 via edge(v1, v3) Notice that the order of the solutions is relevant and is well-defined in Prolog.

24 24 / 65 Different Implementations of can_reach can_reach1(x,x). can_reach1(x,z) :- edge(x,y), can_reach1(y,z). can_reach2(x,x). can_reach2(x,z) :- can_reach2(y,z), edge(x,y). can_reach3(x,z) :- edge(x,y), can_reach3(y,z). can_reach3(x,x). can_reach4(x,z) :- can_reach4(y,z), edge(x,y). can_reach4(x,x).

25 25 / 65 Question Given: edge(v1,v2). edge(v1,v3). edge(v2,v3). edge(v2,v4). For the following queries, what will be the response from Prolog with respect to each implementation of can_reach??- can_reach( v2, v2 ).?- can_reach( X, v2 ).?- can_reach( v2, Y ).?- can_reach( X, X ).?- can_reach( X, Y ).?- can_reach( v1, v3 ).?- can_reach( X, v2 ), fail.?- can_reach( v2, Y ), fail.?- can_reach( X, X ), fail.?- can_reach( X, Y ), fail.

26 26 / 65 For Example edge(v1,v2). edge(v1,v3). edge(v2,v3). edge(v2,v4). can_reach1(x,x). can_reach1(x,z) :- edge(x,y), can_reach1(y,z).?- can_reach1( v2, v2 ).?- can_reach1( X, v2 ).?- can_reach1(v2, Y ).?- can_reach1( X, X ).?- can_reach1( X, Y ).?- can_reach1( v1, v3 ).?- can_reach1( X, v2 ), fail.?- can_reach1( v2, Y ), fail.?- can_reach1( X, X ), fail.?- can_reach1( X, Y ), fail. Similar instances can be created for can_reach2, can_reach3, and can_reach4.

27 27 / 65 Analysis I can_reach1 can_reach2 can_reach3 can_reach4?- can_reach( v2, v2 ). true true true?- can_reach( X, v2 ). X = v2 X = v2 X = v1?- can_reach( v2, Y ). X = v2 X = v2 X = v3?- can_reach( X, X ). X = _G236 X = _G236 X = _G236?- can_reach( X, Y ). X = _G236 X = _G236 X = v1 Y = _G236 Y = _G236 Y = v3 Question : Do we really want to allow X = _G236 as a valid answer to our query? How can we prevent this?

28 28 / 65 Analysis II can_reach1 can_reach2 can_reach3 can_reach4?- can_reach( v1, v3 ). true true true?- can_reach( X, v2 ), fail. false false?- can_reach( v1, Y ), fail. false false?- can_reach( X, X ), fail. false false?- can_reach( X, Y ), fail. false false Note that a response of false means that the search space is finite. Question : What would happen if the graph contained a cycle?

29 29 / 65 Different Implementations of plus nat_a(0). nat_a(s(x)) :- nat_a(x). nat_b(s(x)) :- nat_b(x). nat_b(0). plus1a(0,y,y) plus1a(s(x),y,s(z)) plus2a(s(x),y,s(z)) plus2a(0,y,y) plus1b(0,y,y) plus1b(s(x),y,s(z)) plus2b(s(x),y,s(z)) plus2b(0,y,y) :- nat_a(y). :- plus1a(x,y,z). :- plus2a(x,y,z). :- nat_a(y). :- nat_b(y). :- plus1b(x,y,z). :- plus2b(x,y,z). :- nat_b(y).

30 30 / 65 Termination and Search Space Analysis plus1a plus2a plus1b plus2b?- plus(x, s(0), s(s(s(0))) ). defined defined defined defined?- plus(s(0), Y, s(s(s(0))) ). defined defined defined defined?- plus(x, Y, s(s(s(0))) ). defined defined defined defined?- plus(x, Y, Z ). unbounded number undefined undefined undefined of solutions

31 31 / 65 Outline Control Flow During Execution Tree Traversal A Detailed Trace Search Space Analysis Modelling Equations and Operations Lists

32 32 / 65 Remark In general, care must be taken when defining computations whose sub-computations can involve an exhaustive search of an infinite domain or involve multiple logical variables that can be instantiated to an infinite number of values. Furthermore, in this context great care should be taken when dealing with queries. Especially queries that require multiple solutions to be found or involve the fail predicate. However, when the above conditions can be contained (e.g., at most one unbound variable per query, and only queries for which solutions exist), then Prolog programs can be easily written from a declarative perspective. That is, one simply writes properties in the form of rules or facts that describe the relationships in which we are interested.

33 33 / 65 The trick is to recognize when such benign conditions exist. In the following examples, we will assume friendly queries That is, queries that do not involve multiple uninstantiated variables and do not require the system to produce multiple solutions either as a result of hitting the enter key or the fail predicate. (The above statement is slightly inaccurate for the upcoming examples, but acceptable for this discussion). In the following examples, we focus on the computational power of logic programming rather than its search idiosyncrasies. That is, we shall predominantly focus on expressing search trees that contain the solution in which we are interested. We will not worry so much about whether or not Prolog s search mechanism will actually be able to find the solution. Nevertheless, the programs presented are correct in the sense that Prolog will find solutions to queries when they exist.

34 Built-in Predicates Operator/Predicate Description Example = Explicit Unification X = Y \= Unification failure X \= Y not Failure to satisfy goal not(x = Y ) (use sparingly) =< Less-than or equal-to X =< Y < Less-than X < Y Many other operators and predicates exist, use help menu to see what is available for a given version of Prolog. Note that ordering operators are not defined on terms. 34 / 65

35 Some Basic Prolog Types Type Description Example integer Standard Integers 234 string Standard Strings hello world constant Constant Terms (lower-case ids) hello 35 / 65

36 36 / 65 Complex Terms as Parameters The idea of having a complex term in the parameter of the head of a rule may seem backwards from other programming paradigms. However, this is just a notational short-cut. % a more standard treatment of formal parameters. natural(0). natural(x) :- natural(y), X = s(y). % denotes unification % versus Prolog s treatment of formal parameters natural(0). natural(s(x)) :- natural(x).

37 37 / 65 Modelling the Equation: (x + 1) y = x y + y Multiplication natural(0). natural(s(x)) :- natural(x). plus(0,y,y) :- natural(y). plus(s(x),y,s(z)) :- plus(x,y,z). times(0,y,0) times(s(x),y,z) :- natural(y). :- times(x,y,xy), plus(xy,y,z).

38 38 / 65 Modelling the Equation: x (n+1) = x n x Issue: 0 0 = 1? or 0 0 = undefined? Exponentiation times(0,y,0) times(s(x),y,z) :- natural(y). :- times(x,y,xy), plus(xy,y,z). exp(s(n), 0, 0) :- natural(n). % Base case: 0 (n+1) = 0 exp(0, X, s(0)) :- natural(x). % Base case: X 0 = 1 exp(s(n),x, Result) :- exp(n,x,temp), times(x,temp,result).

39 39 / 65 Modelling the Equation: fact(n) = n fact(n 1) Factorial times(0,y,0) times(s(x),y,z) :- natural(y). :- times(x,y,xy), plus(xy,y,z). factorial(0, s(0)). factorial(s(n), Result) :- factorial(n,temp), times(s(n), Temp Result).

40 40 / 65 Mod : a y + z = x where z < y Modulus % note that the definition below assumes times(+,-,-). % Note that there is an error in the book wrt % Prologs search algorithm mod(x,y,z) :- times(y,a,ay), lt(z,y), plus(ay,z,x).

41 41 / 65 mod(x, y) = mod(x y, y) Modulus - an alternate definition mod(x,y,x) :- lt(x,y). mod(x,y,z) :- plus(y,mxy,x), mod(mxy,y,z). % or mod(x,y,x) :- lt(x,y). mod(x,y,z) :- plus(mxy,y,x), mod(mxy,y,z).

42 42 / 65 Modelling the Equation: gcd(x, y) = gcd(y, x mod y) Greatest Common Divisor % will this work? Can the rules be rearranged? gcd(x,y,gcd) :- mod(x,y,z), gcd(y,z,gcd). gcd(x, 0,X) :- lt(0,x).

43 43 / 65 Outline Control Flow During Execution Tree Traversal A Detailed Trace Search Space Analysis Modelling Equations and Operations Lists

44 44 / 65 List Notation(s) Definition Formal Object Cons pair syntax Element Syntax [] [] [].(a, []) [a []] [a].(a,.(b, [])) [a [b []]] [a, b].(a,.(b,.(c, []))) [a [b [c []]]] [a, b, c].(a, X) [a X] [a X].(a,.(b, X)) [a [b X]] [a, b X]

45 45 / 65 List Basics list([]). list([x Xs]) :- list(xs). % is this antecedent necessary? natural_list([]). natural_list([x Xs]) :- natural(x),natural_list(xs). length([], 0). length([x Xs], s(n)) :- length(xs,n). member(x,[x Xs]). member(x,[y Ys]) :- member(x,ys). % select(x,hasxs,onelessxs). select(x, [X Ys],Ys). select(x,[y Ys],[Y Zs]) :- select(x,ys,zs).

46 46 / 65 Top-down versus Bottom-up Remark There are two ways to recursively construct a list. In the bottom-up approach one begins with an initial value and adds elements to that value. In the top-down approach one begins with an uninstantiated variable and adds values to that variable and then finally the variable is instantiated to an initial value.

47 Problem Continued... Construct a list containing 10 occurrences of the constant b. top_down([],0). top_down([b Xs], N) :- N1 is N 1, top_down(xs,n1).?- top_down(xs,10), write(xs),nl. bottom_up(acc,acc,0). bottom_up(xs,acc,n) :- N1 is N 1, bottom_up(xs, [b Acc], N1).?- bottom_up(xs, [], 10), write(xs),nl. 47 / 65

48 48 / 65 The Accumulator An accumulator is a parameter that is used to accumulate the result of a recursive computation as it progresses towards its base case. When the base case is reached, the accumulated value generally will hold the result of the entire computation. In the base case, this result is then transferred via unification to the argument corresponding to the return value. The general functionality of an accumulator can be described as follows: accumulator( [], Acc, Acc). accumulator( [X Xs], Acc, Result) :-..., accumulator(xs, f(acc,x),result).

49 49 / 65 Tail Recursion Definition In the body of a function/predicate, a recursive call is tail recursive if no computations need to be performed after the recursive call. Operationally, what this means is that when the base case is reached the computation is completed (i.e., the answer that you have at the base case is the answer for the original function/predicate call). In other words, you are computing your answer on the way to the base case, and when the base case is reached the computation is completed. There is a strong correspondence between tail recursive definitions and iterative loops. This enables optimizing compilers to efficiently compile tail recursive function/predicate definitions.

50 50 / 65 Summing a List of Integers % bottom-up and tail-recursive sum1([],sum,sum). sum1([x Xs],Sum,Result) :- Sum1 is Sum + X, sum1(xs,sum1,result). % tail recursive?- sum1([1,2,3],0,s), write(s),nl. % top-down sum2([],0). sum2([x Xs],Sum) :- sum2(xs,sum1), Sum is Sum1 + X. % non-tail recursive?- sum2([1,2,3],s), write(s),nl.

51 51 / 65 Counting the Even Numbers in a List % top-down count_even1([],0). count_even1([x XS],Count) :- count_even1(xs,count1), 0 =:= X mod 2, Count is Count count_even1([x XS],Count1) :- count_even1(xs,count1), 1 =:= X mod 2.?- count_even1([1,2,3,4,5,6,7,8,9,0],x). Remark The symbol =:= is used to denote arithmetic equivalence.

52 52 / 65 Continued... % tail-recursive and bottom-up count_even2([],acc,acc). count_even2([x XS],Acc,Count) :- 0 =:= X mod 2, Acc1 is Acc + 1, count_even2(xs,acc1,count). count_even2([x XS],Acc,Count) :- 1 =:= X mod 2, count_even2(xs,acc,count).?- count_even2([1,2,3,4,5,6,7,8,9,0],0,x).

53 53 / 65 More List Predicates % Top-down construction % Rule of thumb: arguments in head should % be more complex than in the body. append([],ys,ys). append([x Xs],Ys,[X Zs]) :- append(xs,ys,zs). prefix([],ys). prefix([x Xs],[X Ys]) :- prefix(xs,ys). suffix(xs,xs). suffix(xs,[y Ys]) :- suffix(xs,ys).

54 54 / 65 Prefixes and Suffixes prefix suffix sublist(xs,ys) :- prefix(ps,ys), suffix(xs,ps). prefix suffix sublist(xs,ys) :- suffix(ps,ys), prefix(xs,ps).

55 55 / 65 A Recursive Definition of Sublist sublist(xs,ys) :- prefix(xs,ys). sublist(xs,[y Ys]) :- sublist(xs,ys). As Bs Xs % prefix of suffix in terms of append sublist(xs,asxsbs) :- append(as,xsbs,asxsbs), append(xs,bs,xsbs). % suffix of prefix in terms of append sublist(xs,asxsbs) :- append(asxs,bs,asxsbs), append(as,xs,asxs).

56 56 / 65 Reversing the Element Order in a List reverse([],[]). reverse([x Xs],Zs) :- reverse(xs,ys),append(ys,[x],zs). % using an accumulator and tail-recursion. reverse(xs,ys) :- aux_reverse(xs,[],ys). aux_reverse([],acc,acc). aux_reverse([x Xs],Acc,Zs) :- aux_reverse(xs,[x Acc],Zs).?- reverse([1,2,3],ys).?- reverse(xs,[3,2,1]).

57 Problem An Experiment Write a predicate that makes a copy of a list one element at a time. % Notice that the elements in the copied list will have % their order reversed. copy1(xs,ys) :- aux_copy1(xs,[],ys). aux_copy1([],acc,acc). aux_copy1([x Xs],Acc,Zs) :- aux_copy1(xs,[x Acc],Zs). copy2([],[]). copy2([x Xs],[X Ys]) :- copy2(xs,ys). 57 / 65

58 58 / 65 Analysis of copy1 In copy1 the elements are added to an accumulator whose initial value is a ground term that corresponds to the base case. With every recursive call to copy 1, the accumulator acquires more values until finally, when the base case is reached, the value of the accumulator is transferred (through unification) to the result variable. Notice that the accumulator term is more complex in the body of the rule than it is in the head of the rule (i.e., [X Acc] versus Acc). Conceptually, this can be understood as building up the result value in a bottom-up fashion. That is, one begins with the base value and successively adds elements to this value.

59 59 / 65 Analysis of copy2 In copy2 the elements are added to the head of a list whose tail is an uninstantiated variable whose value finally becomes the ground term [] in the base case. Notice that the result term is more complex in the head of the rule than it is in the body of the rule (i.e., [X Ys] versus Ys). Conceptually this can be understood as building up the value in a top-down fashion. That is, one adds values to an uninstantiated variable and then finally instantiates the variable to the base value.

60 60 / 65 Element Deletion % deleting all occurrences of X from a list % Note that the rule order between the second and % third rule is crucial here. How can this be fixed? delete([],x, []). delete([x Xs],X,Ys) :- delete(xs,x,ys). delete([y Xs],X,[Y Ys]) :- delete(xs,x,ys).

61 61 / 65 Continued... % a solution using the predicate not delete([],x, []). delete([x Xs],X,Ys) :- delete(xs,x,ys). delete([y Xs],X,[Y Ys]) :- not(y = X), delete(xs,x,ys). % a solution using the not-unifiable symbol delete([],x, []). delete([x Xs],X,Ys) :- delete(xs,x,ys). delete([y Xs],X,[Y Ys]) :- Y \= X, delete(xs,x,ys).

62 62 / 65 Accumulator-based List Reversal % Using an accumulator - and reversing the list order. delete(xs,x,ys) :- aux_delete(xs,x,ys,[]). % base case, transfer accumulated value to result argument. aux_delete([],x, Acc,Acc). aux_delete([x Xs], X, Ys, Acc) :- aux_delete(xs,x,ys,acc). aux_delete([y Xs], X, Ys, Acc) :- not(y = X), aux_delete(xs,x,ys,[y Acc]).

63 63 / 65 A Sorting Specification sort(xs,ys) :- permutation(xs,ys), ordered(ys). select(x,[x Ys],Ys). select(x,[y Ys],[Y Zs]) :- select(x,ys,zs). permutation([],[]). permutation(xs,[z Ys]) :- select(z,xs,zs), permutation(zs,ys). % the =< operator denotes the less-than-or-equal-to operator. ordered([]). ordered([x]). ordered([x1, X2 Xs]) :- X1 =< X2, ordered([x2 Xs]).

64 64 / 65 Insertion Sort sort([x Xs],Zs) :- sort(xs,ys), insert(x,ys,zs). sort([],[]). insert(x,[],[x]). insert(x,[y Ys],[Y Zs]) :- X > Y, insert(x,ys,zs). insert(x,[y Ys],[X, Y Ys]) :- X =< Y.

65 65 / 65 Quicksort quicksort([x Xs],Ys) :- partition(xs,x,littles,bigs), quicksort(littles,ls), quicksort(bigs,bs), append(ls,[x Bs],Ys). quicksort([],[]). partition([],y,[],[]). partition([x Xs],Y,[X Ls],Bs) :- X =< Y, partition(xs,y,ls,bs). partition([x Xs],Y,Ls,[X Bs]) :- X > Y, partition(xs,y,ls,bs).

Chapter 5. Pure PROLOG. Foundations of Logic Programming

Chapter 5. Pure PROLOG. Foundations of Logic Programming Chapter 5 1 Outline vs. logic programming Lists in Adding Arithmetics to Adding the Cut to 2 Syntax of Pure Prolog p(x,a) :- q(x), r(x,yi). p(x, a) q(x), r(x,y i ) % Comment Ambivalent syntax: p(p(a,b),

More information

CS 360: Programming Language Concepts Lecture 15 Logic Programming

CS 360: Programming Language Concepts Lecture 15 Logic Programming Reference: Ch. 12.1-12.5 CS 360: Programming Language Concepts Lecture 15 Logic Programming I. Logic Programming (Generally) What is logic programming? A logic program is a collection of declarations,

More information

Computational Logic Prolog Programming Basics

Computational Logic Prolog Programming Basics Computational Logic Prolog Programming Basics 1 Overview 1. Using unification 2. Data structures 3. Recursion, backtracking, and search 4. Control of execution 2 Role of Unification in Execution As mentioned

More information

Prolog Programming Basics. Computational Logic. Overview. 3. Recursion, backtracking, and search. 2. Data structures. 1.

Prolog Programming Basics. Computational Logic. Overview. 3. Recursion, backtracking, and search. 2. Data structures. 1. Computational Logic Prolog Programming Basics 1 Overview 1. Using unification 2. Data structures 3. Recursion, backtracking, and search 4. Control of execution 2 Role of Unification in Execution As mentioned

More information

CS 360: Programming Languages Lecture 10: Logic Programming with Prolog

CS 360: Programming Languages Lecture 10: Logic Programming with Prolog CS 360: Programming Languages Lecture 10: Logic Programming with Prolog Geoffrey Mainland Drexel University Section 1 Administrivia Midterm Tuesday Midterm is Tuesday, February 14! Study guide is on the

More information

Lecture Notes on Prolog

Lecture Notes on Prolog Lecture Notes on Prolog 15-317: Constructive Logic Frank Pfenning Lecture 14 October 15, 2009 In this lecture we introduce some simple data structures such as lists, and simple algorithms on them such

More information

Lecture 11: Feb. 10, 2016

Lecture 11: Feb. 10, 2016 CS323: AI (Hands on with Prolog) Spring 2016 Lecturer: K.R. Chowdhary Lecture 11: Feb. 10, 2016 : Professor of CS (VF) Disclaimer: These notes have not been subjected to the usual scrutiny reserved for

More information

Lecture Notes on Prolog

Lecture Notes on Prolog Lecture Notes on Prolog 15-317: Constructive Logic Frank Pfenning Lecture 14 October 27, 2015 In this lecture we introduce some simple data structures such as lists, and simple algorithms on them such

More information

Prolog-2 nd Lecture. Prolog Predicate - Box Model

Prolog-2 nd Lecture. Prolog Predicate - Box Model Prolog-2 nd Lecture Tracing in Prolog Procedural interpretation of execution Box model of Prolog predicate rule How to follow a Prolog trace? Trees in Prolog use nested terms Unification Informally Formal

More information

Logic Programming: Lecture 1

Logic Programming: Lecture 1 Logic Programming: Lecture 1 Madhavan Mukund Chennai Mathematical Institute madhavan@cmi.ac.in PLC, 3 April 2017 Logic programming Programming with relations Variables Names starting with a capital letter

More information

Programming Paradigms

Programming Paradigms PP 2017/18 Unit 12 Functions and Data Types in Haskell 1/45 Programming Paradigms Unit 12 Functions and Data Types in Haskell J. Gamper Free University of Bozen-Bolzano Faculty of Computer Science IDSE

More information

CS206 Lecture 09. Logic Progamming (Prolog) Plan for Lecture 9. Prolog Vocabulary Syntax. Numbers and Structured Data

CS206 Lecture 09. Logic Progamming (Prolog) Plan for Lecture 9. Prolog Vocabulary Syntax. Numbers and Structured Data CS206 Lecture 09 Logic Progamming (Prolog) G. Sivakumar Computer Science Department IIT Bombay siva@iitb.ac.in http://www.cse.iitb.ac.in/ siva Page 1 of 32 Fri, Jan 17, 2003 Plan for Lecture 9 Prolog Vocabulary

More information

simplicity hides complexity flow of control, negation, cut, 2 nd order programming, tail recursion procedural and declarative semantics and & or

simplicity hides complexity flow of control, negation, cut, 2 nd order programming, tail recursion procedural and declarative semantics and & or simplicity hides complexity flow of control, negation, cut, 2 nd order programming, tail recursion simple and/or composition of goals hides complex control patterns not easily represented by traditional

More information

Topic B: Backtracking and Lists

Topic B: Backtracking and Lists Topic B: Backtracking and Lists 1 Recommended Exercises and Readings From Programming in Prolog (5 th Ed.) Readings: Chapter 3 2 Searching for the Answer In order for a Prolog program to report the correct

More information

Prolog. Intro to Logic Programming

Prolog. Intro to Logic Programming Prolog Logic programming (declarative) Goals and subgoals Prolog Syntax Database example rule order, subgoal order, argument invertibility, backtracking model of execution, negation by failure, variables

More information

10 Recursive Programming in Prolog

10 Recursive Programming in Prolog 10 Recursive Programming in Prolog What's in This Set of Notes? Examples Transforming Recursion to Iteration Recursive Comparison Joining Structures Accumulators Mapping Problems 10.1 Examples select_first(x,xs,ys)

More information

Programming Language Concepts: Lecture 22

Programming Language Concepts: Lecture 22 Programming Language Concepts: Lecture 22 Madhavan Mukund Chennai Mathematical Institute madhavan@cmi.ac.in http://www.cmi.ac.in/~madhavan/courses/pl2009 PLC 2009, Lecture 22, 15 April 2009 Logic programming

More information

simplicity hides complexity flow of control, negation, cut, 2 nd order programming, tail recursion procedural and declarative semantics and & or

simplicity hides complexity flow of control, negation, cut, 2 nd order programming, tail recursion procedural and declarative semantics and & or simplicity hides complexity flow of control, negation, cut, 2 nd order programming, tail recursion simple and/or composition of goals hides complex control patterns not easily represented by traditional

More information

Introduction to Programming, Aug-Dec 2006

Introduction to Programming, Aug-Dec 2006 Introduction to Programming, Aug-Dec 2006 Lecture 3, Friday 11 Aug 2006 Lists... We can implicitly decompose a list into its head and tail by providing a pattern with two variables to denote the two components

More information

Implementação de Linguagens 2016/2017

Implementação de Linguagens 2016/2017 Implementação de Linguagens Ricardo Rocha DCC-FCUP, Universidade do Porto ricroc @ dcc.fc.up.pt Ricardo Rocha DCC-FCUP 1 Logic Programming Logic programming languages, together with functional programming

More information

815338A Principles of Programming Languages. Exercise 7 answers

815338A Principles of Programming Languages. Exercise 7 answers 815338A Principles of Programming Languages. Exercise 7 answers The topic of this exercise is logic programming in Prolog. Prolog programs can be executed at https://ideone.com/ or http://www.tutorialspoint.com/codingground.htm.

More information

Introduction. CSc 372. Comparative Programming Languages. 22 : Prolog Lists. Department of Computer Science University of Arizona.

Introduction. CSc 372. Comparative Programming Languages. 22 : Prolog Lists. Department of Computer Science University of Arizona. CSc 372 Comparative Programming Languages 22 : Prolog Lists Introduction Department of Computer Science University of Arizona collberg@gmail.com Copyright c 2011 Christian Collberg Christian Collberg Prolog

More information

Multi-paradigm Declarative Languages

Multi-paradigm Declarative Languages Michael Hanus (CAU Kiel) Multi-paradigm Declarative Languages ICLP 2007 1 Multi-paradigm Declarative Languages Michael Hanus Christian-Albrechts-University of Kiel Programming Languages and Compiler Construction

More information

LOGIC AND DISCRETE MATHEMATICS

LOGIC AND DISCRETE MATHEMATICS LOGIC AND DISCRETE MATHEMATICS A Computer Science Perspective WINFRIED KARL GRASSMANN Department of Computer Science University of Saskatchewan JEAN-PAUL TREMBLAY Department of Computer Science University

More information

Programming Paradigms

Programming Paradigms PP 2017/18 Unit 9 Prolog: Accumulators, Order of Goals/Clauses, and the Cut 1/38 Programming Paradigms Unit 9 Prolog: Accumulators, Order of Goals/Clauses, and the Cut J. Gamper Free University of Bozen-Bolzano

More information

Logic Programming II & Revision

Logic Programming II & Revision Logic Programming II & Revision Gerardo Schneider Department of Informatics University of Oslo 1 Some corrections (1) hsiblings(x,y) :- child(x,parent), child(y,parent), X \== Y, child(x,parent1), child(y,parent2),

More information

Haske k ll An introduction to Functional functional programming using Haskell Purely Lazy Example: QuickSort in Java Example: QuickSort in Haskell

Haske k ll An introduction to Functional functional programming using Haskell Purely Lazy Example: QuickSort in Java Example: QuickSort in Haskell Haskell An introduction to functional programming using Haskell Anders Møller amoeller@cs.au.dk The most popular purely functional, lazy programming language Functional programming language : a program

More information

CS 320: Concepts of Programming Languages

CS 320: Concepts of Programming Languages CS 320: Concepts of Programming Languages Wayne Snyder Computer Science Department Boston University Lecture 04: Basic Haskell Continued o Polymorphic Types o Type Inference with Polymorphism o Standard

More information

Programming Languages 3. Definition and Proof by Induction

Programming Languages 3. Definition and Proof by Induction Programming Languages 3. Definition and Proof by Induction Shin-Cheng Mu Oct. 22, 2015 Total Functional Programming The next few lectures concerns inductive definitions and proofs of datatypes and programs.

More information

An introduction introduction to functional functional programming programming using usin Haskell

An introduction introduction to functional functional programming programming using usin Haskell An introduction to functional programming using Haskell Anders Møller amoeller@cs.au.dkau Haskell The most popular p purely functional, lazy programming g language Functional programming language : a program

More information

Introduction to Logic Programming. Ambrose

Introduction to Logic Programming. Ambrose Introduction to Logic Programming Ambrose Bonnaire-Sergeant @ambrosebs abonnairesergeant@gmail.com Introduction to Logic Programming Fundamental Logic Programming concepts Related to FP General implementation

More information

Logic Programming and Resolution Lecture notes for INF3170/4171

Logic Programming and Resolution Lecture notes for INF3170/4171 Logic Programming and Resolution Lecture notes for INF3170/4171 Leif Harald Karlsen Autumn 2015 1 Introduction This note will explain the connection between logic and computer programming using Horn Clauses

More information

Agenda. CS301 Session 20. A logic programming trick. A simple Prolog program. Introduction to logic programming Examples Semantics

Agenda. CS301 Session 20. A logic programming trick. A simple Prolog program. Introduction to logic programming Examples Semantics CS301 Session 20 Introduction to logic programming Examples Semantics Agenda 1 2 A logic programming trick A two-way translator in two lines of code: translate([],[]). translate([word Words],[Mot Mots])

More information

The Idea Underlying Logic Programming. CSci 8980, Fall 2012 Specifying and Reasoning About Computational Systems An Introduction to Logic Programming

The Idea Underlying Logic Programming. CSci 8980, Fall 2012 Specifying and Reasoning About Computational Systems An Introduction to Logic Programming The Idea Underlying CSci 8980, Fall 2012 Specifying and Reasoning About Computational Systems An Introduction to Department of Computer Science and Engineering University of Minnesota Lectures in Fall

More information

Principles of Programming Languages, Spring 2016 Assignment 5 Logic Programming

Principles of Programming Languages, Spring 2016 Assignment 5 Logic Programming Principles of Programming Languages, Spring 2016 Assignment 5 Logic Programming Submission instructions: a. Submit an archive file named id1_id2.zip where id1 and id2 are the IDs of the students responsible

More information

CPS 506 Comparative Programming Languages. Programming Language Paradigm

CPS 506 Comparative Programming Languages. Programming Language Paradigm CPS 506 Comparative Programming Languages Functional Programming Language Paradigm Topics Introduction Mathematical Functions Fundamentals of Functional Programming Languages The First Functional Programming

More information

Declarative Programming. 7: inductive reasoning

Declarative Programming. 7: inductive reasoning Declarative Programming 7: inductive reasoning 1 Inductive reasoning: overview infer general rules from specific observations Given B: background theory (clauses of logic program) P: positive examples

More information

Part I Logic programming paradigm

Part I Logic programming paradigm Part I Logic programming paradigm 1 Logic programming and pure Prolog 1.1 Introduction 3 1.2 Syntax 4 1.3 The meaning of a program 7 1.4 Computing with equations 9 1.5 Prolog: the first steps 15 1.6 Two

More information

Logic programming I. Henrik Boström Stockholm University. Facts Queries Rules Terms Recursion Lists Negation

Logic programming I. Henrik Boström Stockholm University. Facts Queries Rules Terms Recursion Lists Negation Logic programming I Henrik Boström Stockholm University Facts Queries Rules Terms Recursion Lists Negation Logic programs A logic program consists of facts and rules. A logic program is executed by responding

More information

Advanced Prolog Programming

Advanced Prolog Programming 1 Introduction CIS335, Assignment 4 Advanced Prolog Programming Geraint Wiggins November 12, 2004 This practical is the second self-assessed exercise for MSc students on the Prolog module. It is intended

More information

Shell CSCE 314 TAMU. Haskell Functions

Shell CSCE 314 TAMU. Haskell Functions 1 CSCE 314: Programming Languages Dr. Dylan Shell Haskell Functions 2 Outline Defining Functions List Comprehensions Recursion 3 Conditional Expressions As in most programming languages, functions can

More information

COMP2411 Lecture 20: Logic Programming Examples. (This material not in the book)

COMP2411 Lecture 20: Logic Programming Examples. (This material not in the book) COMP2411 Lecture 20: Logic Programming Examples (This material not in the book) There are several distinct but often equivalent ways to think about logic programs 1. As computing logical consequences of

More information

Declaring Numbers. Bernd Braßel, Frank Huch and Sebastian Fischer. Department of Computer Science, University of Kiel, Germany

Declaring Numbers. Bernd Braßel, Frank Huch and Sebastian Fischer. Department of Computer Science, University of Kiel, Germany Declaring Numbers Bernd Braßel, Frank Huch and Sebastian Fischer Department of Computer Science, University of Kiel, Germany WFLP 2007, Paris, France I m going to present joint work with my colleagues

More information

UNIVERSITETET I OSLO

UNIVERSITETET I OSLO Exam in INF3110, December 12, 2013 Page 1 UNIVERSITETET I OSLO Det matematisk-naturvitenskapelige fakultet Exam in: INF3110 Programming Languages Day of exam: December 12, 2013 Exam hours: 14:30 18:30

More information

Operational Semantics

Operational Semantics 15-819K: Logic Programming Lecture 4 Operational Semantics Frank Pfenning September 7, 2006 In this lecture we begin in the quest to formally capture the operational semantics in order to prove properties

More information

3 Lists. List Operations (I)

3 Lists. List Operations (I) 3 Lists. List Operations (I) The list is the simplest yet the most useful Prolog structure. A list is a sequence of any number of objects. Example 3.1: L = [1, 2, 3], R = [a, b, c], T = [john, marry, tim,

More information

Lecture 21: Relational Programming II. November 15th, 2011

Lecture 21: Relational Programming II. November 15th, 2011 Lecture 21: Relational Programming II November 15th, 2011 Lecture Outline Relational Programming contd The Relational Model of Computation Programming with choice and Solve Search Strategies Relational

More information

CS 340 Spring 2019 Midterm Exam

CS 340 Spring 2019 Midterm Exam CS 340 Spring 2019 Midterm Exam Instructions: This exam is closed-book, closed-notes. Electronic devices of any kind are not permitted. Write your final answers, tidily, in the boxes provided. Scratch

More information

Chapter 15. Functional Programming Languages

Chapter 15. Functional Programming Languages Chapter 15 Functional Programming Languages Copyright 2009 Addison-Wesley. All rights reserved. 1-2 Chapter 15 Topics Introduction Mathematical Functions Fundamentals of Functional Programming Languages

More information

This paper concerns our research on developing a theory and methodology appropriate

This paper concerns our research on developing a theory and methodology appropriate Applying Techniques to Skeletons L. S. Sterling and M. Kirschenbaum This paper concerns our research on developing a theory and methodology appropriate for systematically building complicated Prolog programs.

More information

CS 381: Programming Language Fundamentals

CS 381: Programming Language Fundamentals CS 381: Programming Language Fundamentals Summer 2017 Introduction to Logic Programming in Prolog Aug 2, 2017 Outline Programming paradigms Logic programming basics Introduction to Prolog Predicates, queries

More information

Lecture 16: Logic Programming in Prolog

Lecture 16: Logic Programming in Prolog Lecture 16: Logic Programming in Prolog COMP 524 Programming Language Concepts Stephen Olivier March 26, 2009 Based on slides by A. Block, notes by N. Fisher, F. Hernandez-Campos, and D. Stotts Goal of

More information

Haskell 98 in short! CPSC 449 Principles of Programming Languages

Haskell 98 in short! CPSC 449 Principles of Programming Languages Haskell 98 in short! n Syntax and type inferencing similar to ML! n Strongly typed! n Allows for pattern matching in definitions! n Uses lazy evaluation" F definition of infinite lists possible! n Has

More information

Modern Programming Languages. Lecture LISP Programming Language An Introduction

Modern Programming Languages. Lecture LISP Programming Language An Introduction Modern Programming Languages Lecture 18-21 LISP Programming Language An Introduction 72 Functional Programming Paradigm and LISP Functional programming is a style of programming that emphasizes the evaluation

More information

Functional Programming in Haskell Part I : Basics

Functional Programming in Haskell Part I : Basics Functional Programming in Haskell Part I : Basics Madhavan Mukund Chennai Mathematical Institute 92 G N Chetty Rd, Chennai 600 017, India madhavan@cmi.ac.in http://www.cmi.ac.in/ madhavan Madras Christian

More information

CAP 5602 Summer, Lesson 5: Lists. The topics 1. updating a counter 2. the list structure 3. some useful built-in predicates for lists

CAP 5602 Summer, Lesson 5: Lists. The topics 1. updating a counter 2. the list structure 3. some useful built-in predicates for lists CAP 5602 Summer, 20 Lesson 5: Lists The topics. updating a counter 2. the list structure 3. some useful built-in predicates for lists. Updating a counter Let us try to implement the increse the counter

More information

Introduction to Logic Programming in Prolog 1 / 39

Introduction to Logic Programming in Prolog 1 / 39 Introduction to Logic Programming in Prolog 1 / 39 Outline Programming paradigms Logic programming basics Introduction to Prolog Predicates, queries, and rules Understanding the query engine Goal search

More information

CS 440: Programming Languages and Translators, Spring 2019 Mon

CS 440: Programming Languages and Translators, Spring 2019 Mon Haskell, Part 4 CS 440: Programming Languages and Translators, Spring 2019 Mon 2019-01-28 More Haskell Review definition by cases Chapter 6: Higher-order functions Revisit currying map, filter Unnamed

More information

Bachelor/Master Exam Version V3B

Bachelor/Master Exam Version V3B Prof. aadr. Jürgen Giesl Carsten Otto Bachelor/Master Exam Version V3B First Name: Last Name: Course of Studies (please mark exactly one): Informatik Bachelor TK Master Mathematik Master Other: Maximal

More information

Programming in Pure Prolog

Programming in Pure Prolog Chapter 5 Programming in Pure Prolog We learned in Chapter 3 that logic programs can be used for computing. This means that logic programming can be used as a programming language. However, to make it

More information

Type Systems, Type Inference, and Polymorphism

Type Systems, Type Inference, and Polymorphism 6 Type Systems, Type Inference, and Polymorphism Programming involves a wide range of computational constructs, such as data structures, functions, objects, communication channels, and threads of control.

More information

Lecture 5: Declarative Programming. The Declarative Kernel Language Machine. September 12th, 2011

Lecture 5: Declarative Programming. The Declarative Kernel Language Machine. September 12th, 2011 Lecture 5: Declarative Programming. The Declarative Kernel Language Machine September 12th, 2011 1 Lecture Outline Declarative Programming contd Dataflow Variables contd Expressions and Statements Functions

More information

documenting programs, including: A traditional, command line interactive top level.

documenting programs, including: A traditional, command line interactive top level. Computational Logic Developing Programs with a Logic Programming System 1 Our Development Environment: The Ciao System We use the (ISO-Prolog subset of the) Ciao multiparadigm programming system. In particular,

More information

Logic Programming. CITS 3242 Programming Paradigms. Topic 16: Part IV: Advanced Topics

Logic Programming. CITS 3242 Programming Paradigms. Topic 16: Part IV: Advanced Topics CITS 3242 Programming Paradigms Part IV: Advanced Topics Topic 16: Logic Programming Logic Programming is a paradigm for programming by declaring facts and rules. Programs are executed by querying whether

More information

CS 457/557: Functional Languages

CS 457/557: Functional Languages CS 457/557: Functional Languages Lists and Algebraic Datatypes Mark P Jones Portland State University 1 Why Lists? Lists are a heavily used data structure in many functional programs Special syntax is

More information

SEQUENCES, MATHEMATICAL INDUCTION, AND RECURSION

SEQUENCES, MATHEMATICAL INDUCTION, AND RECURSION CHAPTER 5 SEQUENCES, MATHEMATICAL INDUCTION, AND RECURSION Copyright Cengage Learning. All rights reserved. SECTION 5.5 Application: Correctness of Algorithms Copyright Cengage Learning. All rights reserved.

More information

CSCE 314 TAMU Fall CSCE 314: Programming Languages Dr. Flemming Andersen. Haskell Functions

CSCE 314 TAMU Fall CSCE 314: Programming Languages Dr. Flemming Andersen. Haskell Functions 1 CSCE 314: Programming Languages Dr. Flemming Andersen Haskell Functions 2 Outline Defining Functions List Comprehensions Recursion 3 Conditional Expressions As in most programming languages, functions

More information

COP4020 Programming Languages. Functional Programming Prof. Robert van Engelen

COP4020 Programming Languages. Functional Programming Prof. Robert van Engelen COP4020 Programming Languages Functional Programming Prof. Robert van Engelen Overview What is functional programming? Historical origins of functional programming Functional programming today Concepts

More information

Prolog. GNU Prolog ( SWI-Prolog (

Prolog. GNU Prolog (  SWI-Prolog ( Logic programming Most computations are directed, progressing from an input to an output. In functional programming, this is made very explicit, as the input is the argument of a function and the output

More information

Logic Languages. Hwansoo Han

Logic Languages. Hwansoo Han Logic Languages Hwansoo Han Logic Programming Based on first-order predicate calculus Operators Conjunction, disjunction, negation, implication Universal and existential quantifiers E A x for all x...

More information

Chapter 16. Logic Programming Languages

Chapter 16. Logic Programming Languages Chapter 16 Logic Programming Languages Chapter 16 Topics Introduction A Brief Introduction to Predicate Calculus Predicate Calculus and Proving Theorems An Overview of Logic Programming The Origins of

More information

COMPUTER SCIENCE TRIPOS

COMPUTER SCIENCE TRIPOS CST.0.. COMPUTER SCIENCE TRIPOS Part IA NATURAL SCIENCES TRIPOS Part IA (Paper CS/) POLITICS, PSYCHOLOGY, AND SOCIOLOGY TRIPOS Part I (Paper 9) Monday June 0.0 to 4.0 COMPUTER SCIENCE Paper Answer five

More information

Announcements. The current topic: Scheme. Review: BST functions. Review: Representing trees in Scheme. Reminder: Lab 2 is due on Monday at 10:30 am.

Announcements. The current topic: Scheme. Review: BST functions. Review: Representing trees in Scheme. Reminder: Lab 2 is due on Monday at 10:30 am. The current topic: Scheme! Introduction! Object-oriented programming: Python Functional programming: Scheme! Introduction! Numeric operators, REPL, quotes, functions, conditionals! Function examples, helper

More information

Programming Paradigms

Programming Paradigms PP 2017/18 Unit 18 Summary of Basic Concepts 1/13 Programming Paradigms Unit 18 Summary of Basic Concepts J. Gamper Free University of Bozen-Bolzano Faculty of Computer Science IDSE PP 2017/18 Unit 18

More information

Programming Languages Third Edition

Programming Languages Third Edition Programming Languages Third Edition Chapter 12 Formal Semantics Objectives Become familiar with a sample small language for the purpose of semantic specification Understand operational semantics Understand

More information

Shell CSCE 314 TAMU. Functions continued

Shell CSCE 314 TAMU. Functions continued 1 CSCE 314: Programming Languages Dr. Dylan Shell Functions continued 2 Outline Defining Functions List Comprehensions Recursion 3 A Function without Recursion Many functions can naturally be defined in

More information

Program Verification. Program Verification 307/434

Program Verification. Program Verification 307/434 Program Verification Program Verification 307/434 Outline Introduction: What and Why? Pre- and Postconditions Conditionals while-loops and Total Correctness Arrays Program Verification Introduction 308/434

More information

Bachelor/Master Exam Version V3B

Bachelor/Master Exam Version V3B Prof aadr Jürgen Giesl Carsten Otto Bachelor/Master Exam Version V3B First Name: Last Name: Immatriculation Number: Course of Studies (please mark exactly one): Informatik Bachelor TK Master Mathematik

More information

Typed Racket: Racket with Static Types

Typed Racket: Racket with Static Types Typed Racket: Racket with Static Types Version 5.0.2 Sam Tobin-Hochstadt November 6, 2010 Typed Racket is a family of languages, each of which enforce that programs written in the language obey a type

More information

Chapter 9: Constraint Logic Programming

Chapter 9: Constraint Logic Programming 9. Constraint Logic Programming 9-1 Deductive Databases and Logic Programming (Winter 2007/2008) Chapter 9: Constraint Logic Programming Introduction, Examples Basic Query Evaluation Finite Domain Constraint

More information

15 Unification and Embedded Languages in Lisp

15 Unification and Embedded Languages in Lisp 15 Unification and Embedded Languages in Lisp Chapter Objectives Chapter Contents Pattern matching in Lisp: Database examples Full unification as required for Predicate Calculus problem solving Needed

More information

1.3. Conditional expressions To express case distinctions like

1.3. Conditional expressions To express case distinctions like Introduction Much of the theory developed in the underlying course Logic II can be implemented in a proof assistant. In the present setting this is interesting, since we can then machine extract from a

More information

Scheme Quick Reference

Scheme Quick Reference Scheme Quick Reference COSC 18 Fall 2003 This document is a quick reference guide to common features of the Scheme language. It is not intended to be a complete language reference, but it gives terse summaries

More information

Fundamental mathematical techniques reviewed: Mathematical induction Recursion. Typically taught in courses such as Calculus and Discrete Mathematics.

Fundamental mathematical techniques reviewed: Mathematical induction Recursion. Typically taught in courses such as Calculus and Discrete Mathematics. Fundamental mathematical techniques reviewed: Mathematical induction Recursion Typically taught in courses such as Calculus and Discrete Mathematics. Techniques introduced: Divide-and-Conquer Algorithms

More information

A Small Interpreted Language

A Small Interpreted Language A Small Interpreted Language What would you need to build a small computing language based on mathematical principles? The language should be simple, Turing equivalent (i.e.: it can compute anything that

More information

Topic 5: Examples and higher-order functions

Topic 5: Examples and higher-order functions CITS 3242 Programming Paradigms Topic 5: Examples and higher-order functions This lecture includes some larger examples in F# and introduces higher-functions. 1 Examples: append Now that we have lists,

More information

Functional Logic Programming: From Theory to Curry

Functional Logic Programming: From Theory to Curry Functional Logic Programming: From Theory to Curry Michael Hanus Institut für Informatik, CAU Kiel, D-24098 Kiel, Germany. mh@informatik.uni-kiel.de Abstract. Functional logic programming languages combine

More information

CPL 2016, week 10. Clojure functional core. Oleg Batrashev. April 11, Institute of Computer Science, Tartu, Estonia

CPL 2016, week 10. Clojure functional core. Oleg Batrashev. April 11, Institute of Computer Science, Tartu, Estonia CPL 2016, week 10 Clojure functional core Oleg Batrashev Institute of Computer Science, Tartu, Estonia April 11, 2016 Overview Today Clojure language core Next weeks Immutable data structures Clojure simple

More information

}Optimization Formalisms for recursive queries. Module 11: Optimization of Recursive Queries. Module Outline Datalog

}Optimization Formalisms for recursive queries. Module 11: Optimization of Recursive Queries. Module Outline Datalog Module 11: Optimization of Recursive Queries 11.1 Formalisms for recursive queries Examples for problems requiring recursion: Module Outline 11.1 Formalisms for recursive queries 11.2 Computing recursive

More information

Family Example: Some Facts. respects(barb,dan). respects(barb,katie). respects(dan,brian). respects(dan,barbara).

Family Example: Some Facts. respects(barb,dan). respects(barb,katie). respects(dan,brian). respects(dan,barbara). Family Example: Some Facts respects(barb,dan). respects(barb,katie). respects(dan,brian). respects(dan,barbara). Some Queries?- respects(barb,katie). yes?- respects(barb,x). X=dan; % you type ; and RETURN

More information

Lecture #13: Type Inference and Unification. Typing In the Language ML. Type Inference. Doing Type Inference

Lecture #13: Type Inference and Unification. Typing In the Language ML. Type Inference. Doing Type Inference Lecture #13: Type Inference and Unification Typing In the Language ML Examples from the language ML: fun map f [] = [] map f (a :: y) = (f a) :: (map f y) fun reduce f init [] = init reduce f init (a ::

More information

}Optimization. Module 11: Optimization of Recursive Queries. Module Outline

}Optimization. Module 11: Optimization of Recursive Queries. Module Outline Module 11: Optimization of Recursive Queries Module Outline 11.1 Formalisms for recursive queries 11.2 Computing recursive queries 11.3 Partial transitive closures User Query Transformation & Optimization

More information

Functional Programming. Pure Functional Programming

Functional Programming. Pure Functional Programming Functional Programming Pure Functional Programming Computation is largely performed by applying functions to values. The value of an expression depends only on the values of its sub-expressions (if any).

More information

Symbolic Computation Example Programming Exercises for Prolog

Symbolic Computation Example Programming Exercises for Prolog 2001 July 16 3401 Prolog Programming Exercises Page 1 of 8 Symbolic Computation Example Programming Exercises for Prolog 1. Write a Prolog predicate countbt(tree, Count) to count the number of des in a

More information

The Typed Racket Guide

The Typed Racket Guide The Typed Racket Guide Version 5.3.6 Sam Tobin-Hochstadt and Vincent St-Amour August 9, 2013 Typed Racket is a family of languages, each of which enforce

More information

Logic-Oriented Programming (5/11/2004)

Logic-Oriented Programming (5/11/2004) 1 Logic-Oriented Programming (5/11/2004) Daniel P. Friedman, David W. Mack, William E. Byrd Computer Science Department, Indiana University Bloomington, IN 47405, USA Oleg Kiselyov Fleet Numerical Meteorology

More information

Types of recursion. Structural vs. general recursion. Pure structural recursion. Readings: none. In this module: learn to use accumulative recursion

Types of recursion. Structural vs. general recursion. Pure structural recursion. Readings: none. In this module: learn to use accumulative recursion Types of recursion Readings: none. In this module: learn to use accumulative recursion learn to recognize generative recursion CS 135 Fall 2018 07: Types of recursion 1 Structural vs. general recursion

More information

CS 135 Winter 2018 Tutorial 7: Accumulative Recursion and Binary Trees. CS 135 Winter 2018 Tutorial 7: Accumulative Recursion and Binary Trees 1

CS 135 Winter 2018 Tutorial 7: Accumulative Recursion and Binary Trees. CS 135 Winter 2018 Tutorial 7: Accumulative Recursion and Binary Trees 1 CS 135 Winter 2018 Tutorial 7: Accumulative Recursion and Binary Trees CS 135 Winter 2018 Tutorial 7: Accumulative Recursion and Binary Trees 1 Goals of this tutorial You should be able to... understand

More information

Scheme Quick Reference

Scheme Quick Reference Scheme Quick Reference COSC 18 Winter 2003 February 10, 2003 1 Introduction This document is a quick reference guide to common features of the Scheme language. It is by no means intended to be a complete

More information

LECTURE 16. Functional Programming

LECTURE 16. Functional Programming LECTURE 16 Functional Programming WHAT IS FUNCTIONAL PROGRAMMING? Functional programming defines the outputs of a program as a mathematical function of the inputs. Functional programming is a declarative

More information