Showing posts with label Prolog tutorial. Show all posts
Showing posts with label Prolog tutorial. Show all posts

Friday, 15 February 2019

Prolog: Append elements of a list


Prolog provides append rule, to append the elements of a list.

1 ?- append([], [], X).
X = [].

2 ?- append([], [1, 2], X).
X = [1, 2].

3 ?- append([3, 4], [1, 2], X).
X = [3, 4, 1, 2].

4 ?- append([3, 4], [1, 2, 3], X).
X = [3, 4, 1, 2, 3].


You can even use the append method in other way.

5 ?- append(X, [1, 2, 3], [3, 4, 1, 2, 3]).
X = [3, 4] .

6 ?- append([3, X], [1, 2, 3], [3, 4, 1, 2, 3]).
X = 4.

7 ?- append([3, X], [Y, Z, 3], [3, 4, 1, 2, 3]).
X = 4,
Y = 1,
Z = 2.


Previous                                                 Next                                                 Home

Prolog: convert list of characters to list of integers


Write a program that takes list of characters from a .. z and map a to 1, b t 2… and print the new list.

listDemo.pl
capital(a, 1).
capital(b, 2).
capital(c, 3).
capital(d, 4).
capital(e, 5).
capital(f, 6).
capital(g, 7).
capital(h, 8).
capital(i, 9).
capital(j, 10).
capital(k, 11).
capital(l, 12).
capital(m, 13).
capital(n, 14).
capital(o, 15).
capital(p, 16).
capital(q, 17).
capital(r, 18).
capital(s, 19).
capital(t, 20).
capital(u, 21).
capital(v, 22).
capital(w, 23).
capital(x, 24).
capital(y, 25).
capital(z, 26).

/*Default fallback case*/
capital(X, X).

alter([], []).
alter([Head1|Tail1], [Head2|Tail2]) :- capital(Head1, Head2), alter(Tail1, Tail2).


1 ?- consult(listDemo).
true.

2 ?- alter([1, 2, 3], X).
X = [1, 2, 3].

3 ?- alter([a, b, c], X).
X = [1, 2, 3] .


Previous                                                 Next                                                 Home