Abstract
This chapter describes how the ‘cut’ predicate can be used to prevent undesirable backtracking and how ‘cut’ can be used in conjunction with the ‘fail’ predicate to specify exceptions to general rules.
After reading this chapter you should be able to:
-
Use the cut predicate to prevent unwanted backtracking
-
Use ‘cut with failure’ to specify exceptions to general rules
Access this chapter
Tax calculation will be finalised at checkout
Purchases are for personal use only
Author information
Authors and Affiliations
Practical Exercise 7
Practical Exercise 7
-
(1)
The predicate defined below is intended to correspond to the mathematical function factorial. The factorial of a positive integer N is defined as the product of all the integers from 1 to N inclusive, e.g. the factorial of 6 is 1 × 2 × 3 × 4 × 5 × 6 = 720.
factorial(1,1).
factorial(N,Nfact):-N1 is N-1,
factorial(N1,Nfact1),Nfact is N*Nfact1.
The definition of the factorial predicate is incorrect as given, and using it can cause the system to crash.
Demonstrate that this definition is incorrect by entering a goal such as factorial(6,N). Use backtracking to try to find more than one solution.
Correct the program and use it to find the factorials of 6 and 7.
-
(2)
The following is part of a program that defines a predicate go which prompts the user to input a series of numbers ending with 100 and outputs a message saying whether each is odd or even.
go:-repeat,read_and_check(N,Type),
write(N),write(’ is ’),write(Type),nl,N=:=100.
Complete the program by defining the predicate read_and_check to obtain output such as that given below. Your program should use at least one cut.
-
?- go.
-
Enter next number: 23.
-
23 is odd
-
Enter next number: -4.
-
-4 is even
-
Enter next number: 13.
-
13 is odd
-
Enter next number: 24.
-
24 is even
-
Enter next number: 100.
-
100 is even
-
true.
Rights and permissions
Copyright information
© 2013 Springer-Verlag London
About this chapter
Cite this chapter
Bramer, M. (2013). Preventing Backtracking. In: Logic Programming with Prolog. Springer, London. https://doi.org/10.1007/978-1-4471-5487-7_7
Download citation
DOI: https://doi.org/10.1007/978-1-4471-5487-7_7
Published:
Publisher Name: Springer, London
Print ISBN: 978-1-4471-5486-0
Online ISBN: 978-1-4471-5487-7
eBook Packages: Computer ScienceComputer Science (R0)