Advertisement
rkrahul

pred logic

Jun 17th, 2024
132
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Prolog 1.95 KB | Source Code | 0 0
  1. male(james1).
  2. male(charles1).
  3. male(charles2).
  4. male(james2).
  5. male(george1).
  6. female(catherine).
  7. female(elizabeth).
  8. female(sophia).
  9. parent(charles1, james1).
  10. parent(elizabeth, james1).
  11. parent(charles2, charles1).
  12. parent(catherine, charles1).
  13. parent(james2, charles1).
  14. parent(sophia, elizabeth).
  15. parent(george1, sophia).
  16. mother(M,X):- parent(X,M),female(M),write(M),write(' is Mother of '),write(X),nl.
  17. father(F,X):- parent(X,F),male(F).
  18. sibling(S1,S2):- parent(S1,X), parent(S2,X).
  19. grandfather(G,X) :- parent(Y,G),parent(X,Y).
  20. Exercise -
  21. Implementation:
  22. Write a Prolog predicate reverse_list/2 that works like the built-in predicate
  23. reverse/2 (without using reverse/2).
  24. Program:
  25. % Base case: Reversing an empty list results in an empty list. reverse_list([], []).
  26. % Recursive case: To reverse a non-empty list, append the reversed tail to the head.
  27. reverse_list([Head|Tail], Reversed) :-
  28. reverse_list(Tail, ReversedTail),
  29. append(ReversedTail, [Head], Reversed).
  30.  
  31. Write a Prolog predicate distance/3 to calculate the distance between two points in
  32. the 2-dimensional plane. Points are given as pairs of coordinates.
  33. Program:
  34. distance((X1, Y1), (X2, Y2), Distance) :-
  35. Distance is sqrt((X2 - X1) ** 2 + (Y2 - Y1) ** 2).
  36.  
  37. Write a prolog program to solve Tower of hanoi Problem. Program:
  38. % Predicate to solve Tower of Hanoi problem hanoi(N) :-
  39. move(N, left, middle, right).
  40. % Predicate to move disks
  41. move(1, Source, _, Destination) :-
  42. write('Move top disk from '),
  43. write(Source),
  44. write(' to '),
  45. write(Destination), nl.
  46. move(N, Source, Auxiliary, Destination) :-
  47. N > 1,
  48. M is N - 1,
  49. move(M, Source, Destination, Auxiliary),
  50. move(1, Source, _, Destination),
  51. move(M, Auxiliary, Source, Destination).
  52.  
  53. Write a Prolog predicate fibonacci/2 to compute the nth Fibonacci number.
  54. Program: fibonacci(0, 0).
  55. fibonacci(1, 1).
  56. fibonacci(N, Fib) :-
  57. N > 1,
  58. N1 is N - 1,
  59. N2 is N - 2,
  60. fibonacci(N1, Fib1),
  61. fibonacci(N2, Fib2),
  62. Fib is Fib1 + Fib2.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement