Lab Haskell Programs 2
Lab Haskell Programs 2
Semester: VI
Unit-1
Haskel Programs
Prepared By:
1. Write a Haskell program to take an integer from user and add 10 to it, followed by displaying
the result
-- Main function to get input from the user and print the result
main :: IO ()
main = do
putStrLn "Enter an integer:"
input <- getLine
let number = read input :: Int
print (addTen number)
1
Principles of Programming Languages (19CSE313)
factorial 0 = 1
factorial n = n * factorial (n - 1)
main :: IO ()
main = do
putStrLn "Enter a number to calculate its factorial:"
input <- getLine
let num = read input :: Integer
print (factorial num)
main :: IO ()
main = do
putStrLn "Enter a number to check if it's prime:"
input <- getLine
let num = read input :: Integer
if isPrime num
then putStrLn "Yes, it's a prime number!"
else putStrLn "No, it's not a prime number."
4. Write a program that sums all the even numbers in a list.
main :: IO ()
main = do
let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print ("Sum of even numbers: " ++ show (sumEven numbers))
main :: IO ()
main = do
putStrLn "Enter a number to get the Fibonacci number:"
input <- getLine
let num = read input :: Integer
print (fibonacci num)
2
Principles of Programming Languages (19CSE313)
main :: IO ()
main = do
putStrLn "Enter a string to reverse:"
input <- getLine
putStrLn ("Reversed string: " ++ reverseString input)
main :: IO ()
main = do
putStrLn "Enter a string to check if it's a palindrome:"
input <- getLine
if isPalindrome input
then putStrLn "Yes, it's a palindrome!"
else putStrLn "No, it's not a palindrome."
8. Write a program that filters and squares all the even numbers from a list
main :: IO ()
main = do
let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print ("Squares of even numbers: " ++ show (evenSquares
numbers))
main :: IO ()
main = do
putStrLn "Enter a number to calculate the sum of its digits:"
input <- getLine
let num = read input :: Integer
print ("Sum of digits: " ++ show (sumOfDigits num))
3
Principles of Programming Languages (19CSE313)
10. Write a program that merges two lists into a single list.
main :: IO ()
main = do
let list1 = [1, 2, 3]
let list2 = [4, 5, 6]
print ("Merged List: " ++ show (mergeLists list1 list2))
11. Write a program that finds the maximum number in a list of integers.
main :: IO ()
main = do
let numbers = [10, 20, 50, 40, 30]
print ("Maximum number: " ++ show (findMax numbers))
main :: IO ()
main = do
let numbers = [5, 2, 8, 1, 6, 3]
print ("Sorted List: " ++ show (sortList numbers))
13. Write a program that counts how many times a specific element appears in a list.
main :: IO ()
main = do
let numbers = [1, 2, 2, 3, 3, 3, 4]
print ("Occurrences of 3: " ++ show (countOccurrences 3
numbers))
14. Write a program that zips two lists into a list of tuples.
4
Principles of Programming Languages (19CSE313)
main :: IO ()
main = do
let list1 = [1, 2, 3]
let list2 = ['a', 'b', 'c']
print ("Zipped List: " ++ show (zipLists list1 list2))
15. Write a program that applies a given function to each element of a list.
main :: IO ()
main = do
let numbers = [1, 2, 3, 4, 5]
print ("Squared List: " ++ show (squareList numbers))
16. Write a program that filters out odd numbers from a list of integers.
main :: IO ()
main = do
let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print ("Even numbers: " ++ show (filterOddNumbers numbers))
17. Write a program that calculates the sum of the first elements of a list of tuples.
main :: IO ()
main = do
let tuples = [(1, "a"), (2, "b"), (3, "c")]
print ("Sum of first elements: " ++ show (sumFirstElements
tuples))
18. Write a program that computes the length of a list without using the built-in length function
main :: IO ()
main = do
let numbers = [1, 2, 3, 4, 5]
print ("Length of list: " ++ show (myLength numbers))
5
Principles of Programming Languages (19CSE313)
main :: IO ()
main = do
let numbers = [10, 5, 20, 15]
print ("Maximum element: " ++ show (findMax numbers))
main :: IO ()
main = do
let numbers = [1, 2, 2, 3, 4, 4, 5]
print ("List without duplicates: " ++ show (removeDuplicates
numbers))
main :: IO ()
main = do
let numbers = [10, 20, 30, 40, 50]
print ("Element at index 2: " ++ show (nthElement numbers 2))
22. Write a program that applies a function to both elements of a tuple in a list of tuples.
main :: IO ()
main = do
let tuples = [(1, 2), (3, 4), (5, 6)]
let result = mapTuple ((+1), (*2)) tuples
print ("Mapped tuples: " ++ show result)
23. Write a program that counts the occurrences of each element in a list.
6
Principles of Programming Languages (19CSE313)
where
count y = length . filter (== y)
main :: IO ()
main = do
let numbers = [1, 2, 2, 3, 3, 3, 4]
print ("Element counts: " ++ show (countOccurrences numbers))
24. Write a program that flattens a list of lists into a single list.
main :: IO ()
main = do
let nestedList = [[1, 2], [3, 4], [5, 6]]
print ("Flattened list: " ++ show (flatten nestedList))
main :: IO ()
main = do
putStrLn "Enter base and exponent:"
baseInput <- getLine
expInput <- getLine
let base = read baseInput :: Integer
exp = read expInput :: Integer
print ("Result: " ++ show (power base exp))
26. Write a program to calculate the greatest common divisor (GCD) of two numbers using
Euclid's algorithm.
main :: IO ()
main = do
putStrLn "Enter two numbers to compute their GCD:"
aInput <- getLine
bInput <- getLine
let a = read aInput :: Integer
b = read bInput :: Integer
print ("GCD: " ++ show (gcd' a b))
7
Principles of Programming Languages (19CSE313)
main :: IO ()
main = do
let maybeVal = Just 5
print ("Mapped Maybe value: " ++ show (mapMaybe (*2)
maybeVal))
print ("Mapped Nothing: " ++ show (mapMaybe (*2) Nothing))
main :: IO ()
main = do
let numbers = [1, 2, 3, 4, 5]
print ("Is sorted: " ++ show (isSorted numbers))
let unsortedNumbers = [1, 3, 2, 4]
print ("Is sorted: " ++ show (isSorted unsortedNumbers))
29. Write a program that divides two numbers safely, returning Nothing if the denominator is
zero.
main :: IO ()
main = do
print ("Safe division result: " ++ show (safeDiv 10 2))
print ("Safe division result: " ++ show (safeDiv 10 0))
30. Write a program that defines a simple functor and applies a function to its value.
main :: IO ()
main = do
let boxVal = Box 5
print ("Box after applying fmap: " ++ show (fmap (*2)
boxVal))
8
Principles of Programming Languages (19CSE313)
31. Write a program that filters a list of tuples based on a condition and then applies a function
to the filtered list.
main :: IO ()
main = do
let tuples = [(1, "apple"), (6, "banana"), (4, "cherry"), (7,
"date")]
print ("Filtered and mapped tuples: " ++ show (filterAndMap
tuples))
32. Write a program that merges two sorted lists into one sorted list.
main :: IO ()
main = do
let list1 = [1, 3, 5, 7]
let list2 = [2, 4, 6, 8]
print ("Merged sorted list: " ++ show (mergeSorted list1
list2))
main :: IO ()
main = do
let list = [1, 2, 3]
print ("All subsets: " ++ show (subsets list))
main :: IO ()
main = do
let list1 = [1, 2, 3, 4]
let list2 = [3, 4, 5, 6]
9
Principles of Programming Languages (19CSE313)
35. Write a program that counts the frequency of each element in a list.
main :: IO ()
main = do
let numbers = [1, 2, 2, 3, 3, 3, 4]
print ("Element frequencies: " ++ show (countFrequency
numbers))
36. Write a program to define a binary tree and calculate its size (number of nodes).
main :: IO ()
main = do
let tree = Node 1 (Node 2 Empty Empty) (Node 3 Empty Empty)
print ("Size of the tree: " ++ show (size tree))
37. Write a program to check if a binary tree is balanced. A balanced tree is one where the
height difference between the left and right subtrees is at most 1.
main :: IO ()
main = do
let balancedTree = Node 1 (Node 2 Empty Empty) (Node 3 Empty
Empty)
let unbalancedTree = Node 1 (Node 2 (Node 3 Empty Empty)
10
Principles of Programming Languages (19CSE313)
Empty) Empty
print ("Is balanced: " ++ show (isBalanced balancedTree))
print ("Is balanced: " ++ show (isBalanced unbalancedTree))
main :: IO ()
main = do
print ("Parsed integer: " ++ show (parseInt "123"))
print ("Parsed integer: " ++ show (parseInt "abc"))
39. Write a program that lifts a function to work on Maybe values. This is like applying fmap
to a Maybe.
main :: IO ()
main = do
print ("Lifted function: " ++ show (liftMaybe (*2) (Just 5)))
print ("Lifted function: " ++ show (liftMaybe (*2) Nothing))
40. Write a program that demonstrates a simple Logger monad, which appends logs as it runs.
import Control.Monad
main :: IO ()
11
Principles of Programming Languages (19CSE313)
main = do
let result = runLogger $ do
logMessage "Starting computation."
logMessage "Computation complete."
return 42
print result
41. Write a program that partitions a list into two lists: one with elements that satisfy a
predicate and one with elements that do not.
main :: IO ()
main = do
let numbers = [1, 2, 3, 4, 5, 6]
let (even, odd) = partitionList even numbers
print ("Even numbers: " ++ show even)
print ("Odd numbers: " ++ show odd)
import System.IO
main :: IO ()
main = do
-- Writing to the file
writeFile "example.txt" "Hello, this is a simple file
operation example in Haskell!\n"
putStrLn "Text has been written to 'example.txt'."
12
Principles of Programming Languages (19CSE313)
calculateStats [] _ _ _ = []
calculateStats (p:ps) prevCompletion prevWaiting
prevTurnaround =
let completion = prevCompletion + burstTime p
waiting = prevCompletion - arrivalTime p
turnaround = waiting + burstTime p
in (processId p, waiting, turnaround) : calculateStats ps
completion waiting turnaround
main :: IO ()
main = do
let processes = [Process 1 0 5, Process 2 1 3, Process 3 2 8,
Process 4 3 6]
let stats = fcfsScheduling processes
mapM_ print stats
calculateStats [] _ _ _ = []
calculateStats (p:ps) prevCompletion prevWaiting
prevTurnaround =
let completion = prevCompletion + burstTime p
waiting = prevCompletion - arrivalTime p
turnaround = waiting + burstTime p
in (processId p, waiting, turnaround) : calculateStats ps
completion waiting turnaround
main :: IO ()
main = do
let processes = [Process 1 0 6, Process 2 1 8, Process 3 2 7,
Process 4 3 3]
let stats = sjfScheduling processes
mapM_ print stats
13
Principles of Programming Languages (19CSE313)
main :: IO ()
main = do
let processes = [Process 1 0 10 10, Process 2 0 5 5, Process
3 0 8 8]
let timeQuantum = 4
let completed = roundRobinScheduling processes timeQuantum
putStrLn "Process execution order:"
mapM_ print completed
46. Write a program to perform CPU scheduling using priority scheduling algorithm
calculateStats [] _ _ _ = []
calculateStats (p:ps) prevCompletion prevWaiting
prevTurnaround =
let completion = prevCompletion + burstTime p
waiting = prevCompletion - arrivalTime p
turnaround = waiting + burstTime p
in (processId p, waiting, turnaround) : calculateStats ps
completion waiting turnaround
main :: IO ()
main = do
14
Principles of Programming Languages (19CSE313)
import Data.List
import Data.Function (on)
-- Example usage
main :: IO ()
main = do
let cities = [(0, 0), (1, 2), (2, 4), (3, 1)] -- Example
list of cities
let (optimalPath, minDistance) = bruteForceTSP cities
putStrLn "Optimal path:"
print optimalPath
putStrLn $ "Total distance: " ++ show minDistance
15