COP 4020 Programming Languages Logic Programming with Prolog

  • Slides: 5
Download presentation
COP 4020 Programming Languages Logic Programming with Prolog Prof. Xin Yuan

COP 4020 Programming Languages Logic Programming with Prolog Prof. Xin Yuan

Topic n More on Prolog 10/2/2020 COP 4020 Spring 2014 2

Topic n More on Prolog 10/2/2020 COP 4020 Spring 2014 2

Prolog IO n Input: ¨ ¨ ¨ n seeing(File) /* save current file for

Prolog IO n Input: ¨ ¨ ¨ n seeing(File) /* save current file for later use */ see(File) /* open File */ read(Data) /* read data */ seen /* close file */ Get_char( C ) /* read one character */ Read end_of_file when reaching the end of the file. Output: ¨ ¨ ¨ 10/2/2020 telling(File) /* save for later use */ tell(File) /* open file */ write(Data) /* output data */ nl /* output newline */ Told /* close file */ writef("%s", [A]) /* A is a string */ COP 4020 Spring 2014 3

Prolog Arithmetic n n Arithmetic is needed for computations in Prolog Arithmetic is not

Prolog Arithmetic n n Arithmetic is needed for computations in Prolog Arithmetic is not relational The is predicate evaluates an arithmetic expression and instantiates a variable with the result For example ¨ 10/2/2020 X is 2*sin(1)+1 instantiates X with the results of 2*sin(1)+1 COP 4020 Spring 2014 4

Examples with Arithmetic n A predicate to compute the length of a list: length([],

Examples with Arithmetic n A predicate to compute the length of a list: length([], 0). ¨ length([H|T], N) : - length(T, K), N is K + 1. ¨ n n where the first argument of length is a list and the second is the computed length Example query: ¨ n ? - length([1, 2, 3], X). X = 3 Defining a predicate to compute GCD: gcd(A, A, A). ¨ gcd(A, B, G) : - A > B, N is A-B, gcd(N, B, G). ¨ gcd(A, B, G) : - A < B, N is B-A, gcd(A, N, G). ¨ 10/2/2020 COP 4020 Spring 2014 5