0% found this document useful (0 votes)
8 views13 pages

Declarative Programming

Declarative programming is a programming style that focuses on what the desired outcome is rather than how to achieve it, exemplified by languages like SQL and Prolog. In Prolog, facts and rules are defined to create a knowledge base, allowing users to query for information based on established relationships. The document also contrasts declarative programming with imperative and procedural programming, highlighting the differences in approach and structure.

Uploaded by

levi makokha
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views13 pages

Declarative Programming

Declarative programming is a programming style that focuses on what the desired outcome is rather than how to achieve it, exemplified by languages like SQL and Prolog. In Prolog, facts and rules are defined to create a knowledge base, allowing users to query for information based on established relationships. The document also contrasts declarative programming with imperative and procedural programming, highlighting the differences in approach and structure.

Uploaded by

levi makokha
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Declarative Programming

What is Declarative Programming?

Declarative programming is a style of programming where you write facts and rules, then ask
questions (queries) to get answers from a known situation.

You don't write step-by-step instructions (like in imperative programming); instead, you tell the
computer what you want, not how to get it.

Example: SQL as Declarative Programming

SQL is a good example of a declarative language. You write queries to get results from a
database. For example:

SELECT FirstName, SecondName

FROM Student

WHERE ClassID = '7A'

ORDER BY SecondName;

-This tells the database what you want: students' names from Class 7A, sorted by their second
name — not how to fetch or sort them.

Facts and Rules

In declarative programming:

 A fact is something that is true (e.g., France is a country).

 A rule defines relationships between facts (e.g., France speaks French).

A Declarative Programming Language(Prolog)

Prolog uses predicate logic to express facts and rules.

Writing Facts
In Prolog, you write facts like this:

country(france).

language(france,french).

 All facts use lowercase letters.

 Each statement ends with a full stop (. ).

Sample Knowledge Base

country(france).

country(germany).

country(japan).

country(newZealand).

country(england).

country(switzerland).

language(france,french).

language(germany,german).

language(japan,japanese).

language(newZealand,english).

language(england,english).

language(switzerland,french).

language(switzerland,german).

language(switzerland,italian).

This is a knowledge base of known information.

Querying the Knowledge Base

You can ask questions (queries) to get answers.

Example 1: Find countries that speak English


language(Country,english).

 Country is a variable (starts with a capital letter).

 This returns:

newZealand ;

england.

Example 2: Find languages spoken in Switzerland

language(switzerland,Language).

Returns:

french, german, italian.

Summary

Concept Description
Focuses on what the goal is, not how to
Declarative Programming
achieve it.
Fact A known truth (e.g., country(france).)
Rule A relationship between facts.
A goal or question asked to find matching
Query
facts.
A language for declarative programming
Prolog
using predicate logic.

Example Using Prolog: Language Query

Query:

?- language(switzerland, Language).

🔹 Result:

Language = french ;

Language = german ;

Language = italian.

 This shows all languages spoken in Switzerland.


 Use ; in SWI-Prolog to get the next result.

🔸 Using Rules in Knowledge Bases

Prolog lets us define rules using predicate logic.

Bank Account Interest Knowledge Base Example

Facts:

bankAccount(laila, current, 500.00).

bankAccount(stefan, savings, 50).

bankAccount(paul, current, 45.00).

bankAccount(tasha, savings, 5000.00).

interest(twoPercent, current, 500.00).

interest(onePercent, current, 0).

interest(tenPercent, savings, 5000.00).

interest(fivePercent, savings, 0).

Explanation:

 bankAccount(Name, Type, Amount): Stores info about each account.

 interest(Rate, Type, MinimumAmount): Defines interest rate based on account type


and minimum balance.

Rule to Determine Savings Interest Rate

Prolog Rule:

savingsRate(Name, Rate) :-

bankAccount(Name, Type, Amount),

interest(Rate, Type, Base),


Amount >= Base.

What it does:

 Finds the interest rate a person should get based on:

o Their account type

o The amount they have

o The required minimum balance (Base) for the interest rate

Example Query Using Rule

?- savingsRate(stefan, X).

🔹 Result:

X = fivePercent

 Stefan qualifies for 5% interest in a savings account.

More Sample Queries

?- bankAccount(laila, X, Y).

Result:

X = current,

Y = 500.00

?- bankAccount(victor, X, Y).

Result:

false

 No data for victor.

✅ ACTIVITY 20J – Practice Using the Knowledge Base

1. Query to find Laila’s interest rate

2. savingsRate(laila, X).
3. Query to list all savings account holders

4. bankAccount(Name, savings, _).

5. Add a savings account for Robert

6. bankAccount(robert, savings, 300.00).

7. Add a new rule: interest at 7% if savings >= 2000

8. interest(sevenPercent, savings, 2000.00).

Difference Between Addressing Modes in Assembly

 Learn and explain:

o Immediate addressing

o Direct addressing

o Indirect addressing

o Indexed addressing

Provide examples in assembly language syntax.

2️⃣ Procedural vs Object-Oriented Programming (OOP)

 Procedural:

o Uses functions/procedures

o Focus on how to do tasks (step-by-step)

 OOP:

o Uses objects and classes

o Emphasizes data + behavior

Compare using shape programs from Activities 20B and 20E.

Prolog Knowledge Base for Programming Languages

🔹 Facts:
language(fortran, highLevel).

language(cobol, highLevel).

language(visualBasic, oop).

language(python, highLevel).

language(python, oop).

language(assembly, lowLevel).

language(masm, lowLevel).

translator(assembler, lowLevel).

translator(compiler, highLevel).

🔹 Rule:

teaching(X) :-

language(X, oop),

language(X, highLevel).

a) Add Two Facts About Java:

language(java, highLevel).

language(java, oop).

b) Run These Queries:

?- teaching(X).

?- teaching(masm).

c) Show All Languages Translated by an Assembler:

?- translator(assembler, X).

🧠 Key Concepts Recap


Concept Explanation

Fact A known truth in Prolog (e.g., language(python, oop).)

Rule A logical relationship (e.g., savingsRate(Name, Rate) :- ...)

Query A question asked to the Prolog system

Variable Starts with a capital letter (e.g., X, Name, Rate)

Knowledge Base Collection of facts and rules

Absolutely! Here's a comprehensive and clearly explained summary of the content from the
image on File Processing Operations, useful for both theory and practical programming
understanding:

📂 20.2.1 File Processing Operations – Summary Notes

🔹 What Are File Processing Operations?

 File operations are used to store and retrieve records (like student information) in a
persistent storage format.

 Records can include strings, integers, dates, and booleans.

 Files help access records without reading everything from the beginning, especially
useful in random access files.

💾 Example of a Record Structure

In pseudocode, a record (like student info) can be defined as:

TYPE TstudentRecord

DECLARE name : STRING

DECLARE registerNumber : INTEGER

DECLARE dateOfBirth : DATE

DECLARE fullTime : BOOLEAN

ENDTYPE
This defines a custom record type with four fields.

🔄 Storing Records in a Sequential File

 A sequential file stores records one after another (in the order entered).

 Records are entered into an array and then written one by one to the file using the
PUTRECORD pseudocode command.

✅ Pseudocode for Writing to File

DECLARE studentRecord : ARRAY[1:50] OF TstudentRecord

DECLARE studentFile : STRING

DECLARE counter : INTEGER

counter ← 1

studentFile ← "[Link]"

OPEN studentFile FOR WRITE

REPEAT

OUTPUT "Please enter student details"

OUTPUT "Please enter student name"

INPUT [Link][counter]

IF [Link] <> "" THEN

OUTPUT "Please enter student’s register number"

INPUT [Link][counter]

OUTPUT "Please enter student’s date of birth"


INPUT [Link][counter]

OUTPUT "Please enter True for full-time or False for part-time"

INPUT [Link][counter]

PUTRECORD, studentRecord[counter]

counter ← counter + 1

ELSE

CLOSEFILE(studentFile)

ENDIF

UNTIL [Link] = ""

📥 Reading from a File in Pseudocode

OPEN studentFile FOR READ

counter ← 1

REPEAT

GETRECORD, studentRecord[counter]

OUTPUT studentRecord[counter]

counter ← counter + 1

UNTIL EOF(studentFile)

CLOSEFILE(studentFile)

🧾 Identifier Table
Identifier Description

studentRecord Array of student records to be stored

studentFile Name of the file used for storing the records

counter Keeps track of the number of student records

🔧 Important Pseudocode Terms

Keyword Purpose

PUTRECORD Write a record to a file

GETRECORD Read a record from a file

EOF(file) Checks if end of file has been reached

CLOSEFILE Closes an open file

OPEN file FOR Opens a file for read/write

🐍 Python Version of File Operations

Python uses the pickle module for storing and retrieving objects (like records) in binary files.

✅ Python Code Explanation:

1. Define the Record Structure

import pickle

import datetime

class student:

def __init__(self):

[Link] = ""

[Link] = 0

[Link] = [Link]()
[Link] = True

2. Create and Write to a Binary File

studentRecord = student()

studentFile = open("[Link]", "w+b") # Open file to write in binary

print("Please enter student details")

[Link] = input("Enter student name: ")

[Link] = int(input("Enter register number: "))

# Date of Birth

year = int(input("Enter year of birth: "))

month = int(input("Enter month of birth: "))

day = int(input("Enter day of birth: "))

[Link] = [Link](year, month, day)

# Full-time status

[Link] = bool(input("Enter True for full-time, False for part-time: "))

# Save the object to the file

[Link](studentRecord, studentFile)

[Link]()

3. Read From a Binary File

studentFile = open("[Link]", "rb") # Open file to read

studentRecord = [Link](studentFile)
# Display the student data

print([Link], [Link], [Link],


[Link])

[Link]()

🧠 Key Python Concepts

Concept Explanation

pickle module Used to serialize (save) Python objects

.dump(object, file) Saves the object into a binary file

.load(file) Reads the object back from the binary file

'w+b' Write binary mode

'rb' Read binary mode

Let me know if you'd like the VB or Java versions of the file writing code, or if you want quiz
questions or a worksheet based on this!

Common questions

Powered by AI

Procedural programming structures code as a series of procedural calls, focusing on a sequence of tasks or operations to be carried out, such as using functions and procedures to handle specific tasks. Object-oriented programming (OOP), on the other hand, organizes code around objects and classes and emphasizes encapsulating data and behavior together . Procedural programming might be more suitable for smaller, straightforward applications or when performance is critical, as it allows precise control over the order of operations. OOP is often preferred for larger, complex applications due to its scalability and ability to model real-world concepts easily, which can simplify maintenance and enhance modularity .

Using the pickle module in Python for file processing involves serializing Python objects into binary format for storage, which can then be deserialized during retrieval. This contrasts with traditional file handling where data is typically read and written in text format. Pickle provides advantages in storing complex objects with mixed data types easily, preserving Python object structures in their entirety. This is particularly beneficial when handling nested objects or maintaining data integrity across program sessions. The 'pickle.dump()' and 'pickle.load()' functions simplify code needed to handle objects compared to manually parsing and formatting text files . However, using pickle requires caution regarding security, as loading data from untrusted sources poses a vulnerability .

Declarative programming focuses on describing the desired result without explicitly detailing the steps to achieve it. In contrast, imperative programming involves writing explicit step-by-step instructions for how to perform tasks. For example, in declarative programming using SQL, you specify the data you wish to retrieve (e.g., querying a database for certain records), rather than specifying how to retrieve those records . The implication is that declarative programs are generally more concise and less error-prone because they separate the logic of what is needed from how it is achieved, thus allowing more optimization opportunities for the underlying engine or compiler to handle the execution details.

In Prolog, a rule creates a relationship between facts and allows for inference. It enables complex queries and logical deductions beyond simple data retrieval. For example, the rule 'savingsRate(Name, Rate) :- bankAccount(Name, Type, Amount), interest(Rate, Type, Base), Amount >= Base' defines a relationship that determines the appropriate interest rate based on account type and balance . This capability goes beyond basic fact storage by allowing conditional logic to infer new information from existing data, making Prolog powerful for applications like financial software that must comply with complex regulatory logic or academic settings where dynamic relationships are frequent .

The concept of teaching in Prolog, implemented as a rule like 'teaching(X) :- language(X, oop), language(X, highLevel).' demonstrates the language's ability to deduce properties automatically by evaluating multiple conditions. This rule infers that a language qualifies as 'teaching' if it satisfies both high-level and object-oriented properties . Prolog's engine automates the evaluation, contrasting with traditional programming which would require explicit loops and condition checks. It simplifies reasoning processes in complex domains by encapsulating multi-condition logic into easily readable and maintainable rules, which Prolog can repeatedly apply across its knowledge base .

Declarative approaches like SQL and Prolog are often used in database management and AI rule-based systems. SQL is crucial in handling complex data queries where the user specifies what data is needed without detailing the process. It is chosen for its readability and efficiency in retrieving large datasets . Prolog is used in developing AI applications, such as expert systems and natural language processing, where relationships and rules are more congruent with logical reasoning than step-by-step algorithms. These declarative languages are preferred over procedural ones because they allow developers to focus on the 'what' rather than the 'how', simplifying complex data representation and enhancing optimization by the processing system .

Transitioning from procedural to declarative programming, such as moving from C/C++ to Prolog, involves adapting to a new way of thinking. The primary challenge is the shift from specifying how to perform operations to defining what results are desired. In procedural languages, iteration and state management via explicit control flow are common, whereas declarative paradigms abstract these details away. This can make understanding and controlling flow difficult for those accustomed to procedural logic. Additionally, debugging and performance tuning require different strategies, as declarative systems like Prolog handle recursion and backtracking differently than loops . Understanding and effectively using complex rules and predicates also present a steep learning curve as they require a strong grasp of logical and relational thinking .

Implementing a new interest rule in Prolog's banking knowledge base, such as 'interest(sevenPercent, savings, 2000.00)' for balances over 2000, would immediately influence any future queries that calculate savings interest. When the new rule is in place, future queries checking against savings accounts would automatically consider this new condition when determining applicable interest rates. This dynamic reassessment enhances the decision-making process, as it ensures that all calculations remain accurate and up-to-date with the latest policy changes. Prolog's rule-based design allows this integration seamlessly without modifying multiple sections of the code, thereby preserving system consistency and reducing maintenance overhead .

Rules in Prolog enhance AI applications by offering a powerful means to express conditional logic and infer new knowledge automatically from existing facts through logical predicates. Unlike traditional if-else or case conditions in programming that are often linear and limited to direct data manipulation, Prolog rules can interrelate multiple facts and allow complex reasoning with simple queries. For instance, Prolog can deduce all applicable interest rates for accounts based on complex qualifications with a single rule, enhancing efficiency and expressiveness in managing AI logic . This capability makes Prolog especially suitable for developing expert systems, where knowledge and inference abilities are critical .

Prolog's use of facts and rules allows for straightforward representation of knowledge where data can be appended easily by listing facts, such as countries or languages. Rules define logical relationships and can be used to infer new facts from known ones. For example, a fact could state 'country(france).' and a rule could describe 'language(Country, Language).' . When querying the knowledge base, Prolog searches the facts and applies the rules to provide answers based on logical deductions. Queries like '?- language(switzerland, Language)' return all instances of 'Language' related to 'switzerland', demonstrating the declarative power of inferring information from stored facts .

You might also like