Prolog Exercices
Prolog Exercices
Prolog language
1/2
• average(List, Average): Find the average of a list of numbers.
Exercise 4: Find Maximum Element
Write a Prolog rule to find the maximum element in a list:
• max_element(List, Max): Max is the largest element in List.
Exercise 5: Check for Even Numbers
Define a rule to check if a number is even:
• is_even(X): X is even if it is divisible by 2. Then write a rule to filter out only the
even numbers from a list:
• filter_even(List, EvenList): EvenList contains only the even numbers from List.
Exercise 6: Calculate Factorial
Write a recursive rule to calculate the factorial of a given number:
• factorial(N, Result): Result is the factorial of N.
Exercise 7: Fibonacci Sequence
Create a recursive rule to calculate the Nth Fibonacci number:
• fibonacci(N, Result): Result is the Nth Fibonacci number, with fibonacci(0, 0) and
fibonacci(1, 1) as base cases.
Exercise 8: Reverse a List
Write a rule to reverse a list:
• reverse_list(List, Reversed): Reversed is the list in reverse order of List.
Exercise 9: Find All Ancestors
Using a family tree, create a rule to find all ancestors of a given person:
• all_ancestors(Person, AncestorsList): AncestorsList is a list of all ancestors of
Person.
Exercise 10: Simple Arithmetic Operations
Define rules for basic arithmetic operations (addition, subtraction, multiplication,
division). The rule should take two numbers and return the result:
• add(X, Y, Result): Result is X + Y.
• subtract(X, Y, Result): Result is X - Y.
• multiply(X, Y, Result): Result is X * Y.
• divide(X, Y, Result): Result is X / Y (assume Y ≠ 0).
Exercise 11: Sorting a List
Write a Prolog rule to sort a list of numbers in ascending order:
• sort_list(List, SortedList): SortedList is the sorted version of List.
2/2