Siksha Sarovar

Siksha Sarovar (sikshasarovar.com) is a free educational web application that helps students in India learn programming and prepare for academic and competitive exams. The platform offers structured coding courses (C, C++, Python, Java, HTML, CSS, PHP, Power BI, AI, Machine Learning, Data Science), complete university curriculum notes for BCA/MCA students with previous year question papers, Class 10 and Class 12 CBSE/HBSE school notes, and dedicated preparation material for SSC, UPSC, Banking, Railway and other government exams. Browsing the site is completely free and requires no account. Users may optionally sign in with Google solely to save their learning progress, quiz scores and personal preferences across devices.

Privacy Policy | Terms of Service | Contact Siksha Sarovar | About Siksha Sarovar

v4.0.9 · PWA
Siksha Sarovar logo
Siksha Sarovar
Your Learning Universe

Siksha Sarovar is a free e-learning platform for coding courses, BCA university notes and competitive exam preparation. Optional Google sign-in saves your learning progress across devices.

Initializing knowledge base…
Compiling modules 0%

Lab Practicals: Haskell & Prolog Experiments

Lesson 17 of 17 in the free Functional & Logic Programming notes on Siksha Sarovar, written by Rohit Jangra.

How to use this lesson

The lab list for this subject has two halves — Haskell (experiments 1–6) and Prolog (experiments 7–10). Each practical below names the theory lesson it depends on, gives a complete worked solution, and suggests an extension you can show as "extra work" in your record.

---

Experiment 1 — Installation and study of Haskell

  1. Install GHCup (the official installer) → it provides ghc and ghci.
  2. Verify: ghc --version, then start ghci.
  3. Study tasks to record: evaluate arithmetic expressions, use :type on True, 'a', "hi", (+); load a file with :l; reload with :r.
ghci> :t (+)
(+) :: Num a => a -> a -> a
ghci> :t map
map :: (a -> b) -> [a] -> [b]

Theory: Unit 1 — "The Functional Paradigm & Getting Started with Haskell".

---

Experiment 2 — Defining and using user-defined functions

-- Lab2.hs
square :: Int -> Int
square x = x * x

cube :: Int -> Int
cube x = x * square x

isEven :: Int -> Bool
isEven n = n `mod` 2 == 0

bmi :: Double -> Double -> String
bmi w h
  | v < 18.5  = "Underweight"
  | v < 25.0  = "Normal"
  | otherwise = "Overweight"
  where v = w / (h * h)

Extension: rewrite bmi with if-then-else and compare readability. Theory: Unit 1 — "Basic Types, Definitions & Designing Programs".

---

Experiment 3 — Pattern matching and recursion

factorial :: Integer -> Integer
factorial 0 = 1
factorial n = n * factorial (n - 1)

fib :: Int -> Integer
fib 0 = 0
fib 1 = 1
fib n = fib (n-1) + fib (n-2)

sumDigits :: Int -> Int
sumDigits 0 = 0
sumDigits n = n `mod` 10 + sumDigits (n `div` 10)

gcd' :: Int -> Int -> Int
gcd' a 0 = a
gcd' a b = gcd' b (a `mod` b)

Extension: hand-evaluate factorial 4 in your record (examiners love the rewrite trace). Theory: Unit 2 — "Pattern Matching & Recursion".

---

Experiment 4 — List processing

myLength :: [a] -> Int
myLength []     = 0
myLength (_:xs) = 1 + myLength xs

myReverse :: [a] -> [a]
myReverse = go []
  where go acc []     = acc
        go acc (x:xs) = go (x:acc) xs

evensOnly :: [Int] -> [Int]
evensOnly xs = [ x | x <- xs, even x ]

secondLargest :: [Int] -> Int
secondLargest xs = maximum (filter (/= maximum xs) xs)

Theory: Unit 2 — "Programming with Lists".

---

Experiment 5 — Using functions and list operators

ghci> map (*3) [1..5]
[3,6,9,12,15]
ghci> filter (> 2) [1,5,2,8]
[5,8]
ghci> foldr (+) 0 [1..100]
5050
ghci> zip "abc" [1,2,3]
[('a',1),('b',2),('c',3)]
ghci> takeWhile (< 50) [ x*x | x <- [1..] ]
[1,4,9,16,25,36,49]

Record task: for each call write the type of the function being used. Theory: Unit 2 — "Programming with Lists & Building Vocabulary".

---

Experiment 6 — Type classes and user-defined data types

data Shape = Circle Double | Rect Double Double
  deriving (Show, Eq)

area :: Shape -> Double
area (Circle r) = pi * r * r
area (Rect w h) = w * h

class Describable a where
  describe :: a -> String

instance Describable Shape where
  describe (Circle r) = "circle of radius " ++ show r
  describe (Rect w h) = "rectangle " ++ show w ++ "x" ++ show h

Theory: Unit 2 — "Type Classes" and "Algebraic Data Types".

---

Experiment 7 — Installation and study of Prolog

  1. Install SWI-Prolog; start it with swipl.
  2. Study tasks: load a file ([lab7].), run queries, request alternatives with ;, trace execution with trace. / notrace., get help with help(append/3).
  3. Record the difference between =, is, and =:= with examples.

Theory: Unit 4 — "Programming in Prolog".

---

Experiment 8 — Program to categorise animal characteristics

% facts: properties of animals
hasFeathers(eagle).  hasFeathers(penguin).
givesMilk(cow).      givesMilk(whale).     givesMilk(bat).
coldBlooded(snake).  coldBlooded(frog).
livesInWater(whale). livesInWater(frog).   livesInWater(penguin).
canFly(eagle).       canFly(bat).

% rules: categories
bird(X)      :- hasFeathers(X).
mammal(X)    :- givesMilk(X).
reptileOrAmphibian(X) :- coldBlooded(X).
aquaticMammal(X) :- mammal(X), livesInWater(X).
flyingMammal(X)  :- mammal(X), canFly(X).

?- bird(penguin).          % true
?- aquaticMammal(X).       % X = whale
?- flyingMammal(X).        % X = bat

Extension: add \+ canFly(X) to define flightlessBird/1. Theory: Unit 3 — "Introduction to Logic Programming".

---

Experiment 9 — Program to demonstrate family relationships

parent(dasharath, ram).      parent(dasharath, lakshman).
parent(kaushalya, ram).      parent(sumitra, lakshman).
parent(ram, lav).            parent(ram, kush).
parent(sita, lav).           parent(sita, kush).
male(dasharath). male(ram). male(lakshman). male(lav). male(kush).
female(kaushalya). female(sumitra). female(sita).

father(X, Y)      :- parent(X, Y), male(X).
mother(X, Y)      :- parent(X, Y), female(X).
grandfather(X, Z) :- father(X, Y), parent(Y, Z).
brother(X, Y)     :- parent(P, X), parent(P, Y), male(X), X \= Y.
uncle(X, Y)       :- brother(X, P), parent(P, Y).
ancestor(X, Y)    :- parent(X, Y).
ancestor(X, Y)    :- parent(X, Z), ancestor(Z, Y).

?- grandfather(dasharath, Who).   % Who = lav ; Who = kush
?- uncle(lakshman, Who).          % Who = lav ; Who = kush
?- ancestor(dasharath, kush).     % true

Theory: Unit 3 — "Database & Recursive Programming".

---

Experiment 10 — Integer variables in a Prolog program

% arithmetic with integer variables: is/2 in action
square(X, Y)   :- Y is X * X.
sumTo(0, 0).
sumTo(N, S)    :- N > 0, N1 is N - 1, sumTo(N1, S1), S is S1 + N.

% table of squares from 1 to N (fail-driven loop)
printSquares(N) :-
    between(1, N, I),
    Sq is I * I,
    format("~w^2 = ~w~n", [I, Sq]),
    fail.
printSquares(_).

?- square(7, Y).        % Y = 49
?- sumTo(100, S).       % S = 5050
?- printSquares(5).     % prints the table, then true

Record task: explain in one line why Y = 7 7 would NOT give 49. Theory:* Unit 4 — "Programming in Prolog — Arithmetic".

---

Viva quick-fire (asked nearly every year)

  1. What is referential transparency? (Unit 1)
  2. Differentiate normal-order and applicative-order evaluation. (Unit 1)
  3. State the Church–Rosser theorem in one sentence. (Unit 1)
  4. What does foldr (+) 0 compute? (Unit 2)
  5. Why is Maybe better than returning -1 for "not found"? (Unit 2)
  6. Define unification and MGU. (Unit 3)
  7. What is negation as failure? (Unit 3)
  8. Difference between is, = and =:=. (Unit 4)
  9. Green cut vs red cut. (Unit 4)
  10. What two hidden arguments does a DCG rule carry? (Unit 4)