0% found this document useful (0 votes)
11 views18 pages

Lab Assingment3

tdpl

Uploaded by

mednaveen987
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)
11 views18 pages

Lab Assingment3

tdpl

Uploaded by

mednaveen987
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
You are on page 1/ 18

Lab Session - 3

NAME : M NAVEEN
ROLL NO : 422213

TASK - 1
1) What is the difference between the type Char and the type String? Do the two
expressions 'a' and "a" represent the same value?
In Haskell, the types Char and String are different. Char represents a single character, such as 'a',
while String is essentially a list of characters, denoted as [Char]. For example, the string "a" is a list
containing the single character 'a'. Therefore, the expressions 'a' and "a" do not represent the same
value. The expression 'a' is of type Char, whereas "a" is of type String, which is a list of Char. Though
they may appear similar, they belong to distinct types, with 'a' being a single character and "a" being
a list containing one character.

2)

 inc (square 5) = 26
 square (inc 5) = 36
 average (inc 3) (inc 5) = 5

3)
square :: Num a => a -> a

4)

 square_1 → Valid
 1square → Invalid
 Square → Invalid (for function/variable, valid for constructor)
 square! → Invalid
 square' → Valid
5)
showResult :: Int -> String

showResult x = "The result is " ++ show x

main :: IO ()

main = putStrLn (showResult 123)

6)

showAreaOfCircle :: Float -> String

showAreaOfCircle radius = "The area of a circle with radius " ++ show radius ++ "cm is about " ++
show area ++ " cm^2"

where

area = pi * radius^2

main :: IO ()

main = putStrLn (showAreaOfCircle 12.3)


7)

sort2 :: Ord a => a -> a -> (a, a)

sort2 x y

| x <= y = (x, y)

| otherwise = (y, x)

main :: IO ()

main = do

print (sort1 5 3)

print (sort2 5 3)

8)

almostEqual pair1 pair2

= (pair1 == pair2) || (swap pair1 == pair2)

where

swap (x,y) = (y,x)

Correctness: This definition is correct. It first checks if the pairs are equal (pair1 == pair2), then
checks if swapping pair1 makes it equal to pair2. This effectively covers both orderings of the values.

Style: This is considered good style. It uses a helper function (swap) to handle the reverse case,
making the function clean and easy to understand. The logic is also more abstracted, which can be
seen as a benefit.

9)

isLower :: Char -> Bool

isLower ch = ch `elem` ['a'..'z']

main :: IO ()

main = do

print (isLower 'a')

print (isLower 'Z')


10)

mangle :: String -> String

mangle "" = ""

mangle (x:xs) = xs ++ [x]

main :: IO ()

main = do

print (mangle "Hello")

print (mangle "I")

print (mangle "")

11)

multiples :: Int -> Int -> [Int]

multiples n limit = takeWhile (<= limit) [n, 2*n ..]

divide :: Int -> Int -> Int

divide _ 0 = error "Division by zero"

divide divisor dividend = length (multiples divisor dividend)

main :: IO ()

main = do

print (divide 5 10)

print (divide 5 8)

print (divide 3 10)


12)

import Prelude hiding (length)\

length :: [a] -> Int

length [] = 0

length (_:xs) = 1 + length xs

main :: IO ()

main = do

print (length [1, 2, 3, 4])

print (length "Hello")

print (length [])

13)

 1:[2,3,4]
Value: [1,2,3,4]
Explanation: This constructs a list by prepending 1 to the list [2,3,4].

 1:2:3:4:[]
Value: [1,2,3,4]
Explanation: This constructs a list by prepending 1, 2, 3, and 4 to the empty list [].

 [1,2,3]:[4..7]
Error: This gives a type error.
Explanation: The first element [1,2,3] is a list, and [4..7] is also a list. In Haskell, you
cannot construct a list of lists directly like this without wrapping [1,2,3] in another list. The
correct expression would be [[1,2,3],[4..7]].

 [1,2,3] ++ [4..7]
Value: [1,2,3,4,5,6,7]
Explanation: This concatenates the two lists.
 1:['a','b']
Error: This gives a type error.
Explanation: The 1 is an Int, while ['a','b'] is a list of Char. In Haskell, you cannot mix
types in a list. The correct way to create a list of mixed types would be to use a type that can
hold different types, such as Maybe or Either.

 "abc" ++ "cd"
Value: "abcd"
Explanation: This concatenates two strings.

 "a":"bCc"
Error: This gives a type error.
Explanation: The expression attempts to create a list where the head is a string ("a") and the
tail is also a string ("bCc"). The (:) operator expects the head to be an element and the tail to
be a list. The correct way would be ["a", "bCc"] or "a" : ["bCc"].

 "a" ++ "bCc"
Value: "abCc"
Explanation: This concatenates two strings.

 'a':'b'
Value: ['a', 'b']
Explanation: This creates a list with characters a and b.

 'a':"b"
Value: ['a', 'b']
Explanation: This constructs a list with the character 'a' as the head and 'b' as the tail. The
expression can be interpreted as creating a list where 'a' is the first element, and the list ['b'] is
the tail, resulting in ['a', 'b'].

 [1,4,7] ++ 4:[5:[]]
Value: [1,4,7,4,5]
Explanation: This concatenates the lists. 4:[5:[]] evaluates to [4,5].

 [True,True:[]]
Error: This gives a type error.
Explanation: The first element True is a Bool, while True:[] is a list of Bool. This creates
a nested list instead of a flat list. The correct expression could be [[True], True] or [True]
++ [True].

 True:[True,False]
Value: [True, True, False]
Explanation: This prepends True to the list [True, False].
14)

fact :: Int -> Int

fact n

|n<1 = error "Input must be a positive integer"

| n == 1 = 1

| otherwise = n * fact (n - 1)

main :: IO ()

main = do

print (fact 5)

print (fact 3)

The function fact is a partial function because it does not provide a valid output for all possible
integer inputs. Specifically, it only handles positive integers (i.e., n >= 1). For inputs like 0 or negative
integers, it raises an error, thus failing to produce a valid output.

15)

import Prelude hiding (enumFromTo)

enumFromTo :: Int -> Int -> [Int]

enumFromTo m n

|m>n = []

| otherwise = m : enumFromTo (m + 1) n

main :: IO ()

main = do

print (enumFromTo 3 7)

print (enumFromTo 5 5)

print (enumFromTo 8 3)
16)

countOdds :: [Int] -> Int

countOdds [] = 0

countOdds (x:xs)

| odd x = 1 + countOdds xs

| otherwise = countOdds xs

main :: IO ()

main = do

print (countOdds [1, 6, 9, 14, 16, 22])

print (countOdds [2, 4, 6])

print (countOdds [1, 3, 5, 7])

17)

removeOdd :: [Int] -> [Int]

removeOdd [] = []

removeOdd (x:xs)

| odd x = removeOdd xs

| otherwise = x : removeOdd xs

main :: IO ()

main = do

print (removeOdd [1, 4, 5, 7, 10])

print (removeOdd [2, 3, 4, 5, 6])

print (removeOdd [7, 9, 11])


TASK:02
1)

halves :: [Int] -> [Float]


halves [] = []
halves (x:xs) = (fromIntegral x / 2) : halves xs

main :: IO ()
main = do
print (halves [4, 8, 10, 16])
print (halves [1, 3, 5])
print (halves [])

2)
stack :: [a] -> [a]
stack [] = []
stack (x:xs) = xs ++ [x]

main :: IO ()
main = do
print (stack [1, 2, 3, 4])
3)
fibonacci :: Int -> Integer
fibonacci n
|n<0 = error "Negative input not allowed"
| n == 0 = 0
| n == 1 = 1
| otherwise = fibonacci (n - 1) + fibonacci (n - 2)

main :: IO ()
main = do
print (fibonacci 0)
print (fibonacci 1)
print (fibonacci 6)

4)
factors :: Int -> [Int]
factors n
| n <= 1 = error "Input must be greater than 1"
| otherwise = [x | x <- [2..n-1], n `mod` x == 0]

main :: IO ()
main = do
print (factors 12)
print (factors 15)
print (factors 7)
5)
pivot :: Ord a => a -> [a] -> ([a], [a])
pivot v xs = (filter (<= v) xs, filter (> v) xs)

main :: IO ()
main = do
print (pivot 3 [5, 6, 4, 2, 1, 3])
print (pivot 2 [7, 3, 8, 1, 2])
print (pivot 0 [-1, 0, 1])

6) and 7)
data Tree a = Empty | Node a (Tree a) (Tree a) deriving (Show)

treeHeight :: Tree a -> Int


treeHeight Empty = 0
treeHeight (Node _ left right) = 1 + max (treeHeight left) (treeHeight right)

main :: IO ()
main = do
let tree = Node 'a' (Node 'b' (Node 'd' Empty Empty) (Node 'e' Empty Empty)) (Node 'c' Empty
Empty)
print (treeHeight tree)
8)
merge :: Ord a => [a] -> [a] -> [a]
merge [] ys = ys
merge xs [] = xs
merge (x:xs) (y:ys)
| x <= y = x : merge xs (y:ys)
| otherwise = y : merge (x:xs) ys

main :: IO ()
main = do
print (merge [1, 3, 5] [2, 4, 6])
print (merge [1, 2, 3] [])
print (merge [] [4, 5, 6])

9)
mergeSort :: Ord a => [a] -> [a]
mergeSort [] = []
mergeSort [x] = [x]
mergeSort xs = merge (mergeSort left) (mergeSort right)
where
(left, right) = splitAt (length xs `div` 2) xs

merge :: Ord a => [a] -> [a] -> [a]


merge [] ys = ys
merge xs [] = xs
merge (x:xs) (y:ys)
| x <= y = x : merge xs (y:ys)
| otherwise = y : merge (x:xs) ys
main :: IO ()
main = do
print (mergeSort [5, 3, 8, 1, 2])

10)
sortProp :: (Ord a) => [a] -> Bool
sortProp [] = True
sortProp [x] = True
sortProp (x:y:xs) = x <= y && sortProp (y:xs)

main :: IO ()
main = do
print $ sortProp [1, 2, 3, 4, 5]
print $ sortProp [3, 1, 4, 2, 5]

11)
import Prelude hiding (lookup)
lookup :: Eq a => a -> [(a, b)] -> Maybe b
lookup _ [] = Nothing
lookup key ((k, v):tuples) = if key == k then Just v else lookup key tuples

main :: IO ()
main = do
print (lookup 2 [(0, 'a'), (1, 'b')])
print (lookup 2 [(0, 'a'), (2, 'b'), (2, 'c')])
12)
main :: IO ()
main = mapM_ putStrLn [replace x | x <- [1..100]]
where
replace x
| x `mod` 15 == 0 = "NITAndhra"
| x `mod` 3 == 0 = "NIT"
| x `mod` 5 == 0 = "Andhra"
| otherwise = show x

13)
import Data.List (minimumBy)
import Data.Ord (comparing)

isPrime :: Int -> Bool


isPrime n
|n<2 = False
| otherwise = null [x | x <- [2..isqrt n], n `mod` x == 0]
where isqrt = floor . sqrt . fromIntegral
magicalAlphabets :: [Char]
magicalAlphabets = [c | c <- ['A'..'Z'], isPrime (fromEnum c)]

nearestMagical :: Char -> Char


nearestMagical c = minimumBy (comparing (abs . subtract (fromEnum c) . fromEnum))
magicalAlphabets

convertToMagicalWord :: String -> String


convertToMagicalWord = map nearestMagical

main :: IO ()
main = do
let input = "AFREEN"
let output = convertToMagicalWord input
putStrLn output

14)
josephus :: Int -> Int
josephus n = josephusHelper [1..n] 0

josephusHelper :: [Int] -> Int -> Int


josephusHelper [x] _ = x
josephusHelper xs sword =
let nextSword = (sword + 1) `mod` length xs
newList = take nextSword xs ++ drop (nextSword + 1) xs
in josephusHelper newList nextSword

main :: IO ()
main = do
let input = 100
let output = josephus input
print output

15)
rotate :: Int -> [a] -> [a]
rotate k xs = take len (drop k (cycle xs))
where len = length xs

main :: IO ()
main = do
let input = [1, 2, 3, 4, 5, 6, 7]
let k = 2
let output = rotate k input
print output

16)
pascalsTriangle :: Int -> [[Int]]
pascalsTriangle n = take n (iterate nextRow [1])
where
nextRow row = zipWith (+) (0:row) (row ++ [0])

formatNumber :: Int -> String


formatNumber x = let s = show x in replicate (3 - length s) ' ' ++ s

printPascalsTriangle :: [[Int]] -> IO ()


printPascalsTriangle rows = mapM_ putStrLn formattedRows
where
maxWidth = 3
formattedRows = map (\row -> let spaces = replicate ((maxWidth * (length rows - length row)) `div`
2) ' '
in spaces ++ unwords (map formatNumber row)) rows

main :: IO ()
main = do
let input = 5
let output = pascalsTriangle input
printPascalsTriangle output

17)
import Data.List (sort)
import Data.Map (fromListWith, toList)
groupAnagrams :: [String] -> [[String]]
groupAnagrams strs = map snd (toList (fromListWith (++) [(sort str, [str]) | str <- strs]))

main :: IO ()
main = do
let strs = ["eat", "tea", "tan", "ate", "nat", "bat"]
let anagramGroups = groupAnagrams strs
mapM_ (putStrLn . unwords) anagramGroups
18)
maxSubArray :: [Int] -> Int
maxSubArray nums = maxSubArrayHelper nums 0 0

maxSubArrayHelper :: [Int] -> Int -> Int -> Int


maxSubArrayHelper [] maxCurrent maxGlobal = maxGlobal
maxSubArrayHelper (x:xs) maxCurrent maxGlobal =
let maxCurrent' = max (maxCurrent + x) x
maxGlobal' = max maxGlobal maxCurrent'
in maxSubArrayHelper xs maxCurrent' maxGlobal'

main :: IO ()
main = do
let nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4]
print (maxSubArray nums)

You might also like