Lab Assingment3
Lab Assingment3
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
main :: IO ()
6)
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 ()
sort2 x y
| x <= y = (x, y)
| otherwise = (y, x)
main :: IO ()
main = do
print (sort1 5 3)
print (sort2 5 3)
8)
where
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)
main :: IO ()
main = do
main :: IO ()
main = do
11)
main :: IO ()
main = do
print (divide 5 8)
length [] = 0
main :: IO ()
main = do
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 n
| 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)
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 [] = 0
countOdds (x:xs)
| odd x = 1 + countOdds xs
| otherwise = countOdds xs
main :: IO ()
main = do
17)
removeOdd [] = []
removeOdd (x:xs)
| odd x = removeOdd xs
| otherwise = x : removeOdd xs
main :: IO ()
main = do
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)
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
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)
main :: IO ()
main = do
let input = "AFREEN"
let output = convertToMagicalWord input
putStrLn output
14)
josephus :: Int -> Int
josephus n = josephusHelper [1..n] 0
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])
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
main :: IO ()
main = do
let nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4]
print (maxSubArray nums)